Jonas
Jonas

Reputation: 534

How to use setRetainInstance(boolean)?

Suppose I have a Fragment A. It has an instance variable mViewPager that points to its ViewPager.

In the onCreate(Bundle) of Fragment A, I invoke setRetainInstance(true).

Upon orientation change:

  1. onCreateView(LayoutInflater, ViewGroup, Bundle) is called, and a new view is inflated. So, I have a new ViewPager inside the newly inflated view.

  2. mViewPager points to the original ViewPager upon orientation change.

My question is: how do I get the new ViewPager in (1) to be associated with the retained mViewPager in (2)?

Or should I just use onSaveInstanceState(Bundle)?

Upvotes: 2

Views: 1410

Answers (1)

Derek Fung
Derek Fung

Reputation: 8211

As mentioned in @Selvin's comment, you should let the UI element to be recreated.

Some information which you should know:

setRetainInstance(true) should be used for non-UI Fragment only. And my personal advice would be not to consider this first, unless you are run out of option.

To properly handle a restart, it is important that your activity restores its previous state through the normal Activity lifecycle, in which Android calls onSaveInstanceState() before it destroys your activity so that you can save data about the application state. You can then restore the state during onCreate() or onRestoreInstanceState().

You are right about using onSaveInstanceState(Bundle), in general, you should use to save your state. Please be noted that, it is the state you save, but not the UI or the whole Fragment.

For example, a state can be a count on how many times a button is clicked. Check the link below on how to save state

http://developer.android.com/training/basics/activity-lifecycle/recreating.html#SaveState

Moreover, some UI states, e.g. text inputted in EditText are already handled in the system API. So you only need to handle states you maintained by yourself.

Edit:

If you are new to this, and do not know what you need to save and what do not, simply skip it first, and play around orientation change WITHOUT onSaveInstanceState. Then you would soon find out what is lost in the process, and that would be the state which you need to keep.

Upvotes: 2

Related Questions