本文介绍了什么时候使用saveInstanceState()方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know saveInstanceState() is used to store activity variables, text in EditText, etc.

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

But I have a doubt that should I save state of view?

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

Let me give you a scenario. My view has 3 buttons. On clicking one of them, a WebView is displayed to user (in same activity). Now if app gets killed, should I save state that user was displayed WebView when app got killed and when activity gets recreated display WebView instead of buttons?

其他情况是,我有3个选项卡在视图中.选择每个选项卡将显示不同的视图.如上述情况再次说明,我应该保存该用户上次选择此标签的时间吗?

Other scenario is, I have 3 tabs in view. Selecting each tab shows different view. As explained in above case again should I save that user has last selected this tab?

最好能解释我应该和不应该保存活动状态的情况.

It will be best if you can explain the cases where I should and should not save activity state.

推荐答案

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

The operating system knows when it should re-create your app's previous state (the screen orientation changed or your app was killed in the background by the OS) and when to create a new instance (the user left your app with the back button). The onRestoreInstanceState() method is only called when there's a state to restore (when the system is restoring a previous state, as opposed to creating a new instance of the activity).

那么简短的答案是,如果您覆盖onSaveInstanceState()onRestoreInstanceState(),系统将在适当的时候调用它们,而您不必担心决定何时应该"保存状态. .

The short answer, then, is that if you override onSaveInstanceState() and onRestoreInstanceState(), the system will call them when appropriate, and you don't have to worry about deciding when you "should" save state.

当覆盖onSaveInstanceState()时,是的,您应该保存有关活动状态的所有信息.这是在屏幕方向更改期间使用的方法.考虑一下-如果您旋转手机,您希望当前的应用更改标签页,还是刚刚打开的屏幕消失?

When overriding onSaveInstanceState(), yes, you should save everything about your activity's state. This is the method being used during screen orientation change. Think about it - if you rotate your phone, do you expect the current app to change tabs, or the screen that just opened to disappear?

有关更多信息,请参见有关重新创建活动的Android文档.

For more information, see the Android documentation on recreating an activity.

这篇关于什么时候使用saveInstanceState()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 02:38