gpt4 book ai didi

java - 我的 Activity 在未输入 OnSaveInstanceState 句柄的情况下关闭

转载 作者:行者123 更新时间:2023-12-01 12:16:48 25 4
gpt4 key购买 nike

我通过单击按钮关闭第二个 Activity ,然后触发“finish()”方法。这与按我设备上的后退按钮的效果相同,确实如此。问题是它没有进入 OnSaveInstanceState,这在销毁 Activity 时会发生。结果是,再次重新进入此 Activity 后,savedInstanceState == null,因此我无法保存最后一个变量的状态。

    Button closeButton = (Button) findViewById(R.id.bClose); 
closeButton.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
finish();

最佳答案

摘自 onSaveInstaceState 的官方文档:

Do not confuse this method with activity lifecycle callbacks such as onPause(), which is always called when an activity is being placed in the background or on its way to destruction, or onStop() which is called before destruction. One example of when onPause() and onStop() is called and not this method is when a user navigates back from activity B to activity A: there is no need to call onSaveInstanceState(Bundle) on B because that particular instance will never be restored, so the system avoids calling it. An example when onPause() is called and not onSaveInstanceState(Bundle) is when activity B is launched in front of activity A: the system may avoid calling onSaveInstanceState(Bundle) on activity A if it isn't killed during the lifetime of B since the state of the user interface of A will stay intact.

您有两个关于 onSaveInstanceState 的示例。不被调用。最重要的部分是开头:

Do not confuse this method with activity lifecycle callbacks such as onPause(), which is always called when an activity is being placed in the background or on its way to destruction.

不应该期望 onSaveInstanceState每次都会被调用。此方法允许 Activity 保存其 UI 元素。如果您尝试保留变量值或其他内容(即 View 中包含的值,但应在应用程序的生命周期内使用 - 例如用户名),您应该使用另一种机制,如 SharedPreferences .

来源

Activity.onSaveInstanceState(Bundle) reference

关于java - 我的 Activity 在未输入 OnSaveInstanceState 句柄的情况下关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26948525/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com