Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android widget ImageButton loses image when screen is rotated

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

like image 493
alejom99 Avatar asked Dec 22 '22 03:12

alejom99


1 Answers

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()
like image 162
Mark B Avatar answered Jan 13 '23 09:01

Mark B