Friday, July 26, 2013

Android Widget Views not loaded/empty after changing screen orientation


When testing your Android App Widget, the layout views disappears or get deleted after changing screen orientation to landscape

In my case i was using "RemoteViewsService.RemoteViewsFactory" to populate a ListView inside the widget


Below paragraph copied from here

"When the screen is rotated the entire appwidget is rebuilt using the last RemoteViews object you passed to AppWidgetManager.updateAppWidget(). Thus is it very important that every time you call updateAppWidget() you pass a RemoteViews object that has everything set on it that the widget needs if it were to be completely rebuilt"

So in my case i was using a code to update only one field in the widget and then i run appWidgetManager.updateAppWidget(appWidgetIds[i], remoteViews);

The system caches this last update which includes only one element populated so that when i change orientation it show that cached RemoteView

My Solution:

Instead of using "updateAppWidget" use "partiallyUpdateAppWidget" which does not cause RemoteViews caching


RemoteViews widget=new RemoteViews(this.getPackageName(), R.layout.widget);
widget.setTextViewText(, updatedText);
AppWidgetManager manager = AppWidgetManager.getInstance(this);

 partiallyUpdateAppWidget documentation,%20android.widget.RemoteViews%29

No comments:

Post a Comment