Question

I have to remove / add a layout in an android widget on button click (the button is on the widget).

Here is my code

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        // There may be multiple widgets active, so update all of them
        final int N = appWidgetIds.length;
        for (int i = 0; i < N; i++) {
            updateAppWidget(context, appWidgetManager, appWidgetIds[i]);
        }
    }

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

        if(intent.getAction().equals(ACTION_HIDE_BALANCE)) {
            // CODE TO CHANGE WIDGET UI

        }
    }

    static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {

        CharSequence widgetText = context.getString(R.string.appwidget_text);
        // Construct the RemoteViews object
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);

        Intent intent;
        intent = new Intent(ACTION_HIDE_BALANCE);
        PendingIntent hideBalancePendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        views.setOnClickPendingIntent(R.id.action_wallet_hide_balance, hideBalancePendingIntent);

        intent = new Intent(ACTION_SHOW_BALANCE);
        PendingIntent showBalancePendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        views.setOnClickPendingIntent(R.id.action_wallet_show_balance, showBalancePendingIntent);


        // Instruct the widget manager to update the widget
        appWidgetManager.updateAppWidget(appWidgetId, views);
    }
}

Searching on internet i found the PendingIntent technique to have the onClickListener effect (already added the intent filter in my manifest).

The problem is in the onRecieve() callback: how can I change the widget UI? I have to remove a layout like in rootView.removeView(layoutView);

Thanks in advance.

Was it helpful?

Solution

Ok, i've found that is easy almost as with standard views.

@Override
public void onReceive(Context context, Intent intent) {
    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
    int appWidgetId = 0;

    if(intent.getAction().equals(ACTION_HIDE_BALANCE)) {
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.root_view);
        views.removeAllViews(R.id.view_to_remove);
        appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID);
        appWidgetManager.updateAppWidget(appWidgetId, views);
    }

    super.onReceive(context, intent);
}

Obviusly, had to attach AppWidgetManager.EXTRA_APPWIDGET_ID extra to the onClick PendingIntent

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top