Understanding Fragment’s setRetainInstance(boolean)

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?

5 Answers
5

Leave a Comment