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
267 views
in Technique[技术] by (71.8m points)

android - onCreate being called on Activity A in up navigation

So I have an Activity A and an Activity B. I want Activity A to be able to navigate to Activity B with the press of a button. That works, but when I use the up navigation(the home button in the action bar) to navigate back to Activity A, onCreate() is called again and the old information that the user typed in is lost.

I've seen: onCreate always called if navigating back with intent, but they used Fragments, and I'm hoping not to have to redesign the entire app to use fragments. Is there any way I can stop onCreate() from being called every time Activity A becomes active again?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

This behavior is totally fine and wanted. The system might decide to stop Activities which are in background to free some memory. The same thing happens, when e.g. rotating the device.

Normally you save your instance state (like entered text and stuff) to a bundle and fetch these values from the bundle when the Activity is recreated.

Here is some standard code I use:

private EditText mSomeUserInput;
private int mSomeExampleField;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // TODO inflate layout and stuff
    mSomeUserInput = (EditText) findViewById(R.id.some_view_id);

    if (savedInstanceState == null) {
        // TODO instanciate default values
        mSomeExampleField = 42;
    } else {
        // TODO read instance state from savedInstanceState
        // and set values to views and private fields
        mSomeUserInput.setText(savedInstanceState.getString("mSomeUserInput"));
        mSomeExampleField = savedInstanceState.getInt("mSomeExampleField");
    }
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    // TODO save your instance to outState
    outState.putString("mSomeUserInput", mSomeUserInput.getText().toString());
    outState.putInt("mSomeExampleField", mSomeExampleField);
}

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

...