Saving programmatically added Views on orientation change?

故事扮演 提交于 2021-02-07 14:43:26

问题


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?


回答1:


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




回答2:


The best way for that much information is to add android:configChanges="orientation" to your activity in the manifest, and it will prevent the destroy and relaunch functionality that Android assumes you want. Truthfully I'd suggest adding that to any activity that doesn't have a different layout file for landscape and portrait mode.



来源:https://stackoverflow.com/questions/15858413/saving-programmatically-added-views-on-orientation-change

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