سؤال

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?

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?

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.

هل كانت مفيدة؟

المحلول

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).

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.

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?

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

نصائح أخرى

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top