开发者

Android widget ImageButton loses image when screen is rotated

开发者 https://www.devze.com 2022-12-26 21:57 出处:网络
I have a widget on my home screen with several ImageButtons which have default background images. Through the configuration activity, I can change the image on any of the ImageButtons. The problem is

I have a widget on my home screen with several ImageButtons which have default background images. Through the configuration activity, I can change the image on any of the ImageButtons. The problem is that when the screen is rotated, the image开发者_StackOverflow on the ImageButton disapears and it changes back to the default image.

I don't know why this happens or how to fix it


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, not just one or two things that you want to update on the widget display.

So, in your AppWidgetProvider class, whenever you are updating your appwidget you need to create a RemoteViews object, build up all the view settings for your appwidget using that object, and then make one call to AppWidgetManager.updateAppWidget() when you are done.

My guess is you are doing something like this:

  • Get RemoteViews Object
  • Set the new button image
  • Call updateAppWidget()
  • Get RemoteViews Object
  • Set a pending intent on the button
  • Call updateAppWidget()

When you need to be doing something like this:

  • Get RemoteViews Object
  • Set the new button image
  • Set a pending intent on the button
  • Call updateAppWidget()


mbaird's answer is the one.
But there's another solution though. The solution is to use updateAppWidget when you're creating/updating the whole view of the widget and partiallyUpdateAppWidget when you're changing only part of the view. Then the view is not reset.

Partial update example (show a little sync icon on all widgets):

AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);    
int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(context, Widget.class)); 
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout); 

views.setViewVisibility(R.id.syncImage, View.VISIBLE);

for (int i = 0; i < appWidgetIds.length; i++) {    
    appWidgetManager.partiallyUpdateAppWidget(appWidgetIds[i], views);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号