Starting with the documentation:
public void setRetainInstance (boolean retain)
Control whether a fragment instance is retained across Activity re-creation (such as from a configuration change). This can only be used with fragments not in the back stack. If set, the fragment lifecycle will be slightly different when an activity is recreated:
- onDestroy() will not be called (but onDetach() still will be, because the fragment is being detached from its current activity).
- onCreate(Bundle) will not be called since the fragment is not being re-created.
- onAttach(Activity) and onActivityCreated(Bundle) will still be called.
I have some questions:
-
Does the fragment also retain its view, or will this be recreated on configuration change? What exactly does "retained" mean?
-
Will the fragment be destroyed when the user leaves the activity?
-
Why doesn’t it work with fragments on the back stack?
-
Which are the use cases where it makes sense to use this method?
First of all, check out my post on retained Fragments. It might help.
Now to answer your questions:
Yes, the
Fragment‘s state will be retained across the configuration change. Specifically, “retained” means that the fragment will not be destroyed on configuration changes. That is, theFragmentwill be retained even if the configuration change causes the underlyingActivityto be destroyed.Just like
Activitys,Fragments may be destroyed by the system when memory resources are low. Whether you have your fragments retain their instance state across configuration changes will have no effect on whether or not the system will destroy theFragments once you leave theActivity. If you leave theActivity(i.e. by pressing the home button), theFragments may or may not be destroyed. If you leave theActivityby pressing the back button (thus, callingfinish()and effectively destroying theActivity), all of theActivitys attachedFragments will also be destroyed.There are probably multiple reasons why it’s not supported, but the most obvious reason to me is that the
Activityholds a reference to theFragmentManager, and theFragmentManagermanages the backstack. That is, no matter if you choose to retain yourFragments or not, theActivity(and thus theFragmentManager‘s backstack) will be destroyed on a configuration change. Another reason why it might not work is because things might get tricky if both retained fragments and non-retained fragments were allowed to exist on the same backstack.Retained fragments can be quite useful for propagating state information — especially thread management — across activity instances. For example, a fragment can serve as a host for an instance of
ThreadorAsyncTask, managing its operation. See my blog post on this topic for more information.In general, I would treat it similarly to using
onConfigurationChangedwith anActivity… don’t use it as a bandaid just because you are too lazy to implement/handle an orientation change correctly. Only use it when you need to.