Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
550 views
in Technique[技术] by (71.8m points)

android - EditText not automatically saved on screen orientation change

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.

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?

Edit:

I create the EditText object programmatically, not in XML. This turns out to be related to the problem (see accepted answer below).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is not normal behavior.

First and foremost, ensure that you have IDs assigned to your EditText controls in the layout XML.

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);

That will solve your problem.

Should that fail, you'll need to save and restore state yourself.

Override onSaveInstanceState like so:

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putString("textKey", mEditText.getText().toString());
}

And then restore in OnCreate:

public void onCreate(Bundle savedInstanceState) {
    if(savedInstanceState != null)
    {
        mEditText.setText(savedInstanceState.getString("textKey"));
    }
}

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...