Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving programmatically added Views on orientation change?

I'm having trouble with saving Views on orientation change. So here's what's going on for me. I have a class extending HorizontalScrollView that creates a LinearLayout and a button in it's constructor. More buttons are added to the LinearLayout when a button is clicked. When the activity starts, I set the Action Bar to this custom view and it all works just fine, adding and deleting buttons from the LinearLayout. But, here's where the problem starts. If a switch orientation, onCreate is restarted, so a new instantiation of my custom view is created and set to the Action Bar. Therefore, my custom view returns to the beginning when I switch orientation.

How do I persist the view's hierarchy throughout orientation changes?

like image 409
James Jun Avatar asked Nov 24 '22 01:11

James Jun


1 Answers

When orientation changes activity is destroyed and recreated.

In your manifest add the following to your activity.

      <activity android:name=".MyActivity"
      android:configChanges="orientation|keyboardHidden|screenSize"
      android:label="@string/app_name">
      //Beginning with Android 3.2 (API level 13), the "screen size" also changes when the device switches between portrait and landscape orientation.
      //add screenSize for api 13 and above.   

Now, when one of these configurations change, MyActivity does not restart. Instead, the MyActivity receives a call to onConfigurationChanged(). This method is passed a Configuration object that specifies the new device configuration.

http://developer.android.com/guide/topics/resources/runtime-changes.html

like image 187
Raghunandan Avatar answered May 30 '23 19:05

Raghunandan