How to update App Widget with list view from an Activity

前端 未结 2 1566
你的背包
你的背包 2021-02-19 01:02

I know this has been asked for many times but I went through the documentation from top to bottom, read all answers here and none of them helped. To be honest, each answer says

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-19 01:31

    I had a widget implementation in my project. I have modified the below code so that data in widget can be changed from one of my Activity in application. Only showing the essential code for your specific use case.

    Here I am having a button with text in my widget. Through login button click in my Activity , I am modifying the button text in my widget

    Below is my AppWidgetProvider.java class

    public class AppWidgetTrackAsset extends AppWidgetProvider{
          @Override
          public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
            // Perform this loop procedure for each App Widget that belongs to this provider
            final int N = appWidgetIds.length;
    
            for (int i=0; i


    Below is my Activity where I am updating the widget button text on click of my login button
    LoginActivity.java

    public class LoginActivity extends AppCompatActivity implements View.OnClickListener{
    
      Button loginButton;
      @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_login);
            loginButton=(Button)findViewById(R.id.loginButton);
            loginButton.setOnClickListener(this);
    
        }
        @Override
        public void onClick(View v) {
            if(v.getId() == R.id.loginButton){
                updateWidget();
            }
        }
        private void updateWidget(){
            try {
                Intent updateWidget = new Intent(this, AppWidgetTrackAsset.class);
                updateWidget.setAction("update_widget");
                PendingIntent pending = PendingIntent.getBroadcast(this, 0, updateWidget, PendingIntent.FLAG_CANCEL_CURRENT);
                pending.send();
            } catch (PendingIntent.CanceledException e) {
                Log.e(Constants.UI_LOG,"Error widgetTrial()="+e.toString());
            }
        }
    }
    


    Layout for app widget goes like this

    app_widget_track_asset.xml

    
        

    Below is the manifest file essential part for widget

    
                
                    
                
    
                
            
    

提交回复
热议问题