問題描述
我了解到,當應用程序即將停止或終止時,Android 會自動保存 EditText
對象的內容.但是,在我的應用中,當屏幕方向改變時,EditText
的內容會丟失.
I read that Android automatically saves the content of EditText
objects when an application is about to be stopped or killed. However, in my app the content of an EditText
is lost when screen orientation changes.
這是正常行為嗎?然后我是否必須使用 onSaveInstanceState
/onRestoreInstanceState
手動保存/恢復其內容?或者有沒有更簡單的方法告訴Android保存它并恢復它?
Is it normal behaviour? Do I then have to manually save/restore its content with onSaveInstanceState
/onRestoreInstanceState
? Or is there an easier method to tell Android to save it end restore it?
編輯:
我以編程方式創建 EditText
對象,而不是在 XML 中.事實證明這與問題有關(請參閱下面接受的答案).
I create the EditText
object programmatically, not in XML. This turns out to be related to the problem (see accepted answer below).
推薦答案
這不是正常行為.
首先,確保您在布局 XML 中為 EditText
控件分配了 ID.
First and foremost, ensure that you have IDs assigned to your EditText
controls in the layout XML.
它只需要一個ID,句號.如果您以編程方式執行此操作,除非它有 ID,否則它將丟失狀態.
Edit 1: It just needs an ID, period. If you're doing this programmatically, it will lose state unless it has an ID.
因此,將其用作快速 &骯臟的例子:
So using this as a quick & dirty example:
// 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);
這會解決你的問題.
如果失敗,您需要自己保存和恢復狀態.
Should that fail, you'll need to save and restore state yourself.
像這樣覆蓋 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"
來嘗試完成此操作,這是錯誤的方法.
Also, please don't use android:configChanges="orientation"
to try to accomplish this, it's the wrong way to go.
這篇關于EditText 不會在屏幕方向更改時自動保存的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!