简体   繁体   中英

onSaveInstanceState/onRestoreInstanceState for a dialog

I am trying to figure out how onSaveInstanceState/onRestoreInstanceState work with a dialog. With an Acitivity it is easy since they are invoked when the Activity is killed/restarted.

Our Activity displays a login dialog. When is the onSaveInstanceState/onRestoreInstanceStateof the dialog called?

Does it get called automatically when we unbundle the object?

@theblitz: Yes, it is somewhat inconvenient to manage the lifecycle of a Dialog from an Activity.

I had getter methods in the Dialog to retrieve its state variables and I then store these in the Activity's Bundle. Upon onResume or onCreate of the Activity, I retrieve the stored variables from the Bundle, and pass them to the Dialog's parameterized constructor to create a new Dialog. So now I have a Dialog that gives the illusion of being innately state-maintained.

The documents in Dialog say:

Note: Activities provide a facility to manage the creation, saving and restoring of dialogs. See {@link Activity#onCreateDialog(int)}, {@link Activity#onPrepareDialog(int, Dialog)}, {@link Activity#showDialog(int)}, and {@link Activity#dismissDialog(int)}.

So if you want to know When is the onSaveInstanceState/onRestoreInstanceState of the dialog called? You should create your dialog in Activity#onCreateDialog(int) and show you dialog Activity#showDialog(int) . You can see Activity#performSaveInstanceState , it will call Activity#saveManagedDialogs . But you should use DialogFragment now.

Dialogs shouldn't be used or expected to work like regular activities. They should be used to gather user input or display information. You can create custom layouts for them using UI elements such as checkboxes, textviews etc and capture the user information and store it for later usage.

In your login dialog, get the user data by creating a custom layout with textviews for username, password etc, Store this info in your app and later use it however you like.

Here's a excellent guide for the official docs on how to properly use dialogs:

http://developer.android.com/guide/topics/ui/dialogs.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM