Why use Fragment#setRetainInstance(boolean)?

How do you as a developer use this

Call setRetainInstance(true). I typically do that in onCreateView() or onActivityCreated(), where I use it.

and why does it make things easier?

It tends to be simpler than onRetainNonConfigurationInstance() for handling the retention of data across configuration changes (e.g., rotating the device from portrait to landscape). Non-retained fragments are destroyed and recreated on the configuration change; retained fragments are not. Hence, any data held by those retained fragments is available to the post-configuration-change activity.


It's very helpful in keeping long running resources open such as sockets. Have a UI-less fragment that holds references to bluetooth sockets and you won't have to worry about reconnecting them when the user flips the phone.

It's also handy in keeping references to resources that take a long time to load like bitmaps or server data. Load it once, keep it in a retained fragment, and when the activity is reloaded it's still there and you don't have to rebuild it.


Added this answer very late, but I thought it would make things clearer. Say after me. When setRetainInstance is:

FALSE

  • Fragment gets re-created on config change. NEW INSTANCE is created.
  • ALL lifecycle methods are called on config change, including onCreate() and onDestroy().

TRUE

  • Fragment does not get re-created on config change. SAME INSTANCE is used.
  • All lifecycle methods are called on config change, APART FROM onCreate() and onDestroy().
  • Retaining an instance will not work when added to the backstack.

Don't forget that the above applies to DialogFragments as well as Fragments.