【问题标题】:onSavedInstanceState doesn't save my InstanceonSavedInstanceState 不保存我的实例
【发布时间】:2020-03-18 10:24:52
【问题描述】:

希望你们在这些艰难时期一切都好。

我有 2 个活动,A 和 B。

A 有一个按钮,可以让 Intent 从 A 转到 B。B 本身有一个 Dialog 窗口,其 cancel 按钮可以让 Intent 从 B 转到 A。

我想从 A 中保存一些数据(2 个 EditTexts 的内容),所以当我回到 A 时,我不必重新输入那些 EditTexts。

所以在查阅了文档和一些 StackOverflow 之后,我决定使用 onSavedInstance 方法,但我想知道意图转换是否会破坏 Activity 以及因此也破坏了 savedInstance...

这是我的简化代码 - 活动 A:

public class A extends AppCompatActivity {
    Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_match);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        if (savedInstanceState != null) {
            EditText firstPlayer = findViewById(R.id.firstPlayerName);
            EditText secondPlayer = findViewById(R.id.secondPlayerName);

            String firstPlayerName = savedInstanceState.getString("firstPlayerName");
            String secondPlayerName = savedInstanceState.getString("secondPlayerName");

            firstPlayer.setText(firstPlayerName);
            secondPlayer.setText(secondPlayerName);
        }

    }

@Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);

        EditText firstPlayer = findViewById(R.id.firstPlayerName);
        EditText secondPlayer = findViewById(R.id.secondPlayerName);
        String firstPlayerName = String.valueOf(firstPlayer.getText());
        String secondPlayerName = String.valueOf(secondPlayer.getText());
        savedInstanceState.putString("firstPlayerName", firstPlayerName);
        savedInstanceState.putString("secondPlayerName", secondPlayerName);
    }

}

当我调试它时,我注意到它通过 onSavedInstance 并保存了值,但是一旦在 onCreate 中,savedInstanceState 为空。

有什么建议吗?

在此先感谢并照顾好人们。

票价。

【问题讨论】:

    标签: java android android-intent android-activity


    【解决方案1】:

    您注意到“取消按钮使 Intent 能够从 B 转到 A。”。这听起来像是您正在创建 Activity A 的新实例(因此您的 Activity 堆栈变为 A、B、A),并且实例状态特定于单个实例。

    相反,您应该通过简单地在 B 上调用 finish() 返回到 A。这将返回到 A 的原始实例,其中将包含您的数据。

    【讨论】:

    • 嘿瑞恩。感谢您的回答。所以在 B 中我应该调用 ``finish()ˋ` 方法,对吗?那应该把我送回 A,因为我从 A 给 B 打过电话。我会试试的
    • 要添加到此答案,只要您在启动 Activity B 时不调用 A 中的 finish(),当您在 B 中调用 finish() 时,A 应该按预期恢复 @Fares
    • 非常感谢 Ryan 和 @MichaelStoddart,我也会查看活动堆栈!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多