当用户按下“返回”按钮时保持对象的状态

Lui*_*ndo 5 android restore android-edittext

我有一个应用程序,可以在其中以编程方式创建EditText视图。我使用setId()

myEditText.setId(100);
Run Code Online (Sandbox Code Playgroud)

以便 Android 在暂停/停止应用程序时自动保存该对象的状态(正如我在此处被建议做的那样)。它适用于以下情况:

  • (1) 当我使用“主页”按钮离开应用程序时:如果我然后返回应用程序,对象的状态(显示的文本)将按预期恢复。
  • (2) 在屏幕方向更改时(这涉及 Android 自动销毁 Activity 并通过 恢复它Bundle)。对象状态也被保留。

但是,在这种情况下它不起作用

  • (3) 当我使用“返回”按钮离开应用程序时:如果我再回到应用程序,EditText对象是空的。

关于为什么会发生这种情况的任何解释?Android 真的区分使用“主页”和“返回”离开应用程序吗?根据该文件,对象的状态应该会自动保存,通过Bundle即使当活动被销毁。这显然发生在情况(2)中。但不是在情况(3)!

如果这是正常行为,我如何在用户按下“返回”时自动保存和恢复应用程序的状态?我知道我可以为此使用 SharedPreferences,但我宁愿让 Android 自动执行此操作,就像在情况 (1) 和 (2) 中一样。

至少在 Android 4.0 和 4.2 中会发生这种情况(我还没有测试过其他版本)。

Lui*_*ndo 1

我想我找到了解释。我只需要更仔细地阅读文档(感谢@lentz 提供其中一个链接);请参阅此处此处

当您的 Activity 由于用户按“后退”键或 Activity 自行完成而被销毁时,系统对该 Activity 实例的概念将永远消失,因为该行为表明不再需要该 Activity。

如果用户按下“后退”按钮,当前活动将从堆栈中弹出并销毁。堆栈中的先前活动将恢复。当活动被销毁时,系统不会保留活动的状态。

上面解释了我的问题中的行为 (3)。

However, if the system destroys the activity due to system constraints (rather than normal app behavior), then although the actual Activity instance is gone, the system remembers that it existed such that if the user navigates back to it, the system creates a new instance of the activity using a set of saved data that describes the state of the activity when it was destroyed. The saved data that the system uses to restore the previous state is called the "instance state" and is a collection of key-value pairs stored in a Bundle object.

The above probably explains behaviour (1) and (2).

What I don't see is why the user pressing Back should be interpreted as "the activity is no longer needed" ("its state needs not be preserved"). But that's a different matter.