EditText 不会在屏幕方向更改时自动保存

EditText not automatically saved on screen orientation change(EditText 不会在屏幕方向更改时自动保存)

本文介绍了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 不会在屏幕方向更改时自动保存

基础教程推荐