简体   繁体   中英

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

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM