Android widget ImageButton loses image when screen is rotated

佐手、 提交于 2020-01-02 05:25:07

问题


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 on the ImageButton disapears and it changes back to the default image.

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


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/2653270/android-widget-imagebutton-loses-image-when-screen-is-rotated

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