Search code examples
androidandroid-layoutandroid-widgetandroid-pendingintentremoteview

Changing layout when button clicked on widget


I have a widget. What I want to do is to change a layout when button is clicked.

This is what I'm doing:

public class MainWidgetProvider extends AppWidgetProvider {

    public static String ACTION_MENU_CLICKED = "MenuClicked";

    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

        Intent intent = new Intent(context, MainWidgetProvider.class);
        intent.setAction(ACTION_MENU_CLICKED);

        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.main_widget_layout);

        views.setOnClickPendingIntent(R.id.button2, pendingIntent);
    }


    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);

        if (intent.getAction().equals(ACTION_MENU_CLICKED)) {
            AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);

            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.main_widget_layout);

            views.setViewVisibility(R.id.layout1,View.INVISIBLE);
            views.setViewVisibility(R.id.layout2,View.VISIBLE);

            final int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
            appWidgetManager.updateAppWidget(appWidgetId, views);

        }
    }
}

Where is my problem? The code as it now does nothing.


Solution

  • In your onUpdate update your code like this-

    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    
            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.main_widget_layout);
    
            views.setOnClickPendingIntent(R.id.button2, pendingIntent);
    appWidgetManager.updateAppWidget(appWidgetIds, views);//you are missing this line.
    

    and in your onReceive method replace appWidgetId with-

    int[] appWidgetId = AppWidgetManager.getInstance(context).getAppWidgetIds(
                new ComponentName(context, MainWidgetProvider.class));