EditText上没有自动保存在屏幕上的方向变化 [英] EditText not automatically saved on screen orientation change

查看:143
本文介绍了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 ?还是有更简单的方法来告诉机器人将其保存结束恢复吗?

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.

修改1:它只是需要一个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"));
    }
}

另外,请不要使用机器人:configChanges =定向来尝试实现这一目标,这是错误的方式去

Also, please don't use android:configChanges="orientation" to try to accomplish this, it's the wrong way to go.

这篇关于EditText上没有自动保存在屏幕上的方向变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆