简体   繁体   English

在运行时更改小部件背景

[英]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). 我正在开发一个简单的小部件,我想在运行时从png文件(或类似文件)更改背景。 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. 文件YOUR_BACKGROUND是png。

The views Object is an instance of RemoteViews . views对象是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. 您可以使用setInt或RemoteViews中的其他方法来设置背景图像或任何其他值。

remoteViews.setInt(R.id.widget_layout, "setBackgroundResource", R.drawable.myshape_red); 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. 但是,您需要传递一个“ id”,而不只是布局参考。

Please note that this does not work with 2.1. 请注意,这不适用于2.1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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