问题描述
目前我的工作是动态创建控件的Android应用程序。每次用户会点击一个新的EditText出现的按钮下面一个按钮,用户可以与的EditText交互。但是,如果屏幕的方向发生变化,EditText上的也创建的用户消失。
Currently I am working on an Android application that is dynamically creating controls. Everytime a user would click a button a new EditText appears below the button and the user can interact with the EditText. However if the screen orientation changes, the EditText's that the user created also disappears.
code的用户创建的EditText样本:(位于的onClick(),p为基本layoutParamas和布局是位于undearneath该按钮的LinearLayout)
Code sample of user creating a EditText: (located in a onClick(), p is basic layoutParamas, and layout is a LinearLayout located undearneath the button)
EditText editText = new EditText(this);
layout.addView(buttonView, p);
想知道什么是保存布局时,屏幕方向改变了,所以我不丢失任何控件的最简单的方法,还是我dyanmically创建控件错误的。
Wondering what would be the easiest way to save the layout when the screen orientation changes so I do not loose any of the controls, or am I dyanmically creating the controls wrong.
感谢。
更新:通过覆盖的onSaveInstanceState()我能救它包含了所有用户orignally添加的控件列表的对象。使用这个名单我能够在OnCreate创建控件()。
update: By overriding the onSaveInstanceState() I was able to save a object which contained a list of all the controls the user orignally added. Using this list I was able to create the controls in the onCreate().
不过好奇,如果有一个更简单的方法来完成这项任务,因为我将不得不重构很多code,充分实现此方法。
Still curious if there is an easier way to accomplish this task, as I would have to refactor a lot of code to fully implement this method.
推荐答案
尝试添加到您<活性GT;
在清单文件标记:
Try adding this to your <activity>
tag in your manifest file:
android:configChanges="orientation|keyboardHidden"
然后为此在活动类:
Then do this in the activity class:
@Override
public void onConfigurationChanged(final Configuration newConfig)
{
// Ignore orientation change to keep activity from restarting
super.onConfigurationChanged(newConfig);
}
如果你这样做你的活动将只是在方向变化,而不是破坏了重用/重建。所以你不会有救一切你都怎么回事的状态。
If you do this your activity will just be reused on orientation change instead of destroyed/recreated. So you won't have to save the state of everything you have going on.
这篇关于安卓:动态创建控件和方向变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!