我看到安卓系统在应用即将被停止或关闭时会自动保存EditText
对象的内容。然而,在我的应用中,当屏幕方向改变时,EditText
的内容会丢失。
这是正常行为吗?那么我需要使用onSaveInstanceState
/onRestoreInstanceState
手动保存/恢复它的内容吗?还是有更简单的方法告诉安卓系统保存并恢复它?
编辑:
我在代码中动态创建了EditText
对象,而不是在XML中创建。这与问题有关(请参见下面的接受答案)。
我看到安卓系统在应用即将被停止或关闭时会自动保存EditText
对象的内容。然而,在我的应用中,当屏幕方向改变时,EditText
的内容会丢失。
这是正常行为吗?那么我需要使用onSaveInstanceState
/onRestoreInstanceState
手动保存/恢复它的内容吗?还是有更简单的方法告诉安卓系统保存并恢复它?
编辑:
我在代码中动态创建了EditText
对象,而不是在XML中创建。这与问题有关(请参见下面的接受答案)。
这不是正常的行为。
首先,请确保您在布局XML中为您的EditText
控件分配了ID。
编辑1:它只需要一个ID,无论如何。如果您是通过编程方式执行此操作,则除非具有ID,否则它将失去状态。
因此,以此作为快速而简单的示例:
// Find my layout
LinearLayout mLinearLayout = (LinearLayout) findViewById(R.id.ll1);
// Add a new EditText with default text of "test"
EditText testText = new EditText(this.getApplicationContext());
testText.setText("test");
// This line is the key; without it, any additional text changes will
// be lost on rotation. Try it with and without the setId, text will revert
// to just "test" when you rotate.
testText.setId(100);
// Add your new EditText to the view.
mLinearLayout.addView(testText);
那将解决你的问题。
如果那行不通,你需要自己保存和恢复状态。
像这样重写onSaveInstanceState
:
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("textKey", mEditText.getText().toString());
}
然后在 OnCreate
中进行恢复:
public void onCreate(Bundle savedInstanceState) {
if(savedInstanceState != null)
{
mEditText.setText(savedInstanceState.getString("textKey"));
}
}
另外,请不要使用android:configChanges="orientation"
来尝试完成此操作,这是错误的做法。
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("myObj", myObj);
}
在我的对象类实现了Serializable接口并且在onCreate()方法中:
if (savedInstanceState != null && savedInstanceState.getSerializable("myObj") != null) {
myObj = ((MyObj) savedInstanceState.getSerializable("myObj"));
}
可能的原因之一是你重写了onSaveInstanceState方法,但忘记调用父类的同名方法。
super.onSaveInstanceState(outState);
活动中所有视图的状态都会自动保存,除非你覆盖了此功能。即使这很明显,也有可能犯错误。
android:freezesText="true"
吗?editText.setFreezesText(true);
但它没有起作用。 - Luis Mendo编辑文本只需要有一个唯一标识符。如果您动态添加编辑文本,请确保没有相同的ID,否则可能会导致无法恢复文本。 同样,如果您在xml中添加,请使用唯一的ID。希望这能帮助某些人。
顺便说一下:EditText默认情况下设置为setFreezesText为true。
static int testTextId = View.generateViewId()
,然后在testText.setId(ClassName.testTextId)
中使用它。这样你就不必发明一个硬编码的ID整数了。 - Ted Henry