EditText not automatically saved on screen orientation change(EditText 不会在屏幕方向更改时自动保存)
问题描述
我了解到,当应用程序即将停止或终止时,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 不会在屏幕方向更改时自动保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:EditText 不会在屏幕方向更改时自动保存
基础教程推荐
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01