在向上导航中对活动 A 调用 onCreate [英] onCreate being called on Activity A in up navigation

查看:41
本文介绍了在向上导航中对活动 A 调用 onCreate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个活动 A 和一个活动 B.我希望活动 A 能够通过按下按钮导航到活动 B.这是有效的,但是当我使用向上导航(操作栏中的主页按钮)导航回活动 A 时,再次调用 onCreate() 并且用户输入的旧信息丢失了.

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.

我已经看到:onCreate 总是在有意导航时调用,但他们使用了 Fragments,我希望不必重新设计整个应用程序来使用 Fragments.有什么办法可以阻止每次活动 A 再次激活时调用 onCreate()?

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?

推荐答案

这种行为完全没问题,也很受欢迎.系统可能会决定停止在后台运行的 Activity 以释放一些内存.同样的事情发生,例如旋转设备.

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.

通常,您将实例状态(例如输入的文本和内容)保存到一个包中,并在重新创建 Activity 时从包中获取这些值.

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

这篇关于在向上导航中对活动 A 调用 onCreate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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