0

我知道saveInstanceState()用于存储活动变量、EditText 中的文本等。

但我怀疑我应该保存视图状态吗?

让我给你一个场景。我的视图有 3 个按钮。单击其中一个时,会向用户显示一个 WebView(在同一活动中)。现在,如果应用程序被杀死,我是否应该保存当应用程序被杀死时用户显示 WebView 以及重新创建活动时显示 WebView 而不是按钮的状态?

其他情况是,我有 3 个选项卡在视图中。选择每个选项卡会显示不同的视图。如上例所述,我是否应该保存该用户最后一次选择此选项卡?

如果你能解释我应该和不应该保存活动状态的情况,那将是最好的。

4

2 回答 2

2

操作系统知道何时应该重新创建您的应用程序的先前状态(屏幕方向更改或您的应用程序在后台被操作系统杀死)以及何时创建一个新实例(用户使用后退按钮离开您的应用程序)。该onRestoreInstanceState()方法仅在有要恢复的状态时调用(当系统正在恢复以前的状态,而不是创建活动的新实例时)。

那么,简短的回答是,如果您覆盖onSaveInstanceState()and onRestoreInstanceState(),系统将在适当的时候调用它们,您不必担心决定何时“应该”保存 state

覆盖时onSaveInstanceState(),是的,您应该保存有关活动状态的所有内容。这是屏幕方向更改期间使用的方法。想一想——如果你旋转手机,你是否希望当前的应用程序改变标签,或者刚刚打开的屏幕消失?

有关详细信息,请参阅有关重新创建活动的 Android 文档

于 2013-08-13T12:31:49.547 回答
1

I have not done very much research on savedIntanceState on app gets killed. But yes you may save maybe a integer variable (referring to which button is clicked) in state, so that when activity is recreated, you know which webview used to be shown (or none). Same goes to your second situation.

Some extra use case of saved instance state:

One of the most used scenario is during user switches orientation, say you have a couple of edit texts on screen, their holding texts would be gone if user change his device orientation. Saved instance state helps you to recover the entered texts.

Another situation is you will most likely have a few class variable in your activity, probably used to save what user has done, or some temporary list object in a list activity. Saving those variables also prevents you from needing to recover the data on orientation change.

于 2013-08-13T12:13:13.210 回答