a.p.
a.p.

Reputation: 3288

Changing widget background at runtime

I am developing a simple widget and I would like to change the background at runtime from a png file (or similar). Is this possible to do and if so, how? Can someone provide some simple example?

Thanks

Upvotes: 0

Views: 2131

Answers (3)

L.Butz
L.Butz

Reputation: 2616

Use something like:

views.setImageViewBitmap(R.id.widgetBackground, ((BitmapDrawable)context.getResources().getDrawable(R.drawable.YOUR_BACKGROUND)).getBitmap());

File YOUR_BACKGROUND is a png.

The views Object is an instance of RemoteViews. You can get the instance by using:

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

And don't forget to update the Widget after these changes.

AppWidgetManager mgr = AppWidgetManager.getInstance(context);
ComponentName me = new ComponentName(context, Widget.class);
mgr.updateAppWidget(me, views);

Upvotes: 4

Archimedes Trajano
Archimedes Trajano

Reputation: 41220

You can set the background image or any other value using the setInt or other methods in RemoteViews.

remoteViews.setInt(R.id.widget_layout, "setBackgroundResource", R.drawable.myshape_red);

The above sample is what I used to change the widget to another drawable shape. You need to pass in an "id" rather than just the layout reference though.

Please note that this does not work with 2.1.

Upvotes: 1

dimsuz
dimsuz

Reputation: 9207

Did you try View.setBackgroundResource(int resId)?

Upvotes: 0

Related Questions