保存以编程方式添加的方向更改视图? [英] Saving programmatically added Views on orientation change?
问题描述
我在保存有关方向更改的视图时遇到问题.所以这就是我的情况.我有一个扩展 HorizontalScrollView 的类,它在它的构造函数中创建一个 LinearLayout 和一个按钮.单击按钮时,会向 LinearLayout 添加更多按钮.当活动开始时,我将操作栏设置为这个自定义视图,它一切正常,从 LinearLayout 添加和删除按钮.但是,这就是问题开始的地方.如果切换方向,onCreate 将重新启动,因此会创建我的自定义视图的新实例并将其设置为操作栏.因此,当我切换方向时,我的自定义视图返回到开头.
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?
推荐答案
当方向改变时,Activity 被销毁并重新创建.
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.
现在,当这些配置之一发生变化时,MyActivity 不会重新启动.相反,MyActivity 会收到对 onConfigurationChanged() 的调用.此方法会传递一个 Configuration 对象,该对象指定新的设备配置.
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
这篇关于保存以编程方式添加的方向更改视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!