Home » Android » android – Setting AppWidget background for one widget affects others too

android – Setting AppWidget background for one widget affects others too

Posted by: admin May 14, 2020 Leave a comment


The layout file for my widget begins at the top level with:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="#20000000" >

So, the starting background is semi-transparent. Then at some point during execution, I call the following to make the background fully transparent:

remoteViews.setInt(R.id.widget, "setBackgroundColor", Color.parseColor("#00000000"));
appWidgetManager.updateAppWidget(appWidgetId, remoteViews);

Whilst this works, what I’m finding is that when another widget is added, the background for that widget starts off as fully transparent rather than semi-transparent as per the layout xml. It’s as if setting the background color for one widget has changed it for all, including new widgets added subsequently.

Now this is odd, because at the same time as the above snippet, I also add a bitmap into the widget (via the RemoteViews) with:

remoteViews.setImageViewBitmap(R.id.imageView, bmp);

… and that bitmap doesn’t appear in all subsequent widgets, so the basic method I’m using seems to be sound.

So why is the background propagating to other widgets?

EDIT to add derivation of appWidgetId as requested in comment:

Basically the comes from an Intent, e.g. in onCreate() of the configuration Activity for the widget:

Intent intent = getIntent();
Bundle extras = intent.getExtras();
int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
How to&Answers:

In Your AppWidgetProvider class you override onUpdate method. The last parameter is appWidgetIds that is an array of current active widgets ids. Most probably you implemented changing the background color there looping through that array for each widgetId. To be able to define a custom background for each widget, you will need to implement a logic of mapping a needed background to the specific widgetId and respect that logic inside the loop.