Just update a widget RemoteViews instead of completly creating a new one?

孤街醉人 提交于 2019-12-04 13:24:24

问题


So in my onUpdate method in my AppWidgetProvider class, I ended up executing a non-trivial amount of code so that I can completely recreate a new RemoteViews object. The reality is I really only need to be setting the text in one of the textviews in the RemoteViews each time I update. Is there anyway to just modify the RemoteViews that a particular widget is already using?

-Kurtis


回答1:


First, RemoteView is not a View. It's a set of instructions that build a View hierarchy. It is used to recreate a View in another process (App Widgets do not execute in your app's process). As such it's serializable and mutable.

So, when you initialize a RemoteView just store a reference to it somewhere, e.g. in a field of your custom AppWidgetProvider. Next time you need it, get it from field and the change something on it. For changing the string in a TextView use setString(..).

remoteView.setString(textViewId, "setText", "some text for TextView")



回答2:


This is the 2013 update if you are using current API's. In your WidgetProvider class' method that will perform an update:

AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
rv = new RemoteViews(context.getPackageName(), R.layout.widgetlayout); 
rv.setTextViewText(R.id.ofTextViewInWidgetLayoutXML, "Hello World");
appWidgetManager.partiallyUpdateAppWidget(appWidgetIds[i], rv);

Note that it is no longer remoteView.setString but remoteView.setTextViewText




回答3:


You can update the remote views and then call

ComponentName componentName= new ComponentName(context, YourClass.class);
AppWidgetManager.getInstance(context).updateAppWidget(componentName, remoteViews);

on, which AFAIK should update the widget



来源:https://stackoverflow.com/questions/4528824/just-update-a-widget-remoteviews-instead-of-completly-creating-a-new-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!