Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

Android - retaining fragment?

Writer Andrew Mclaughlin

Hi I have a question about retaining fragment when Activity is recreated. I heard one way is to use setRetainFragment(true) in the onCreate method. Question is - how is this different from keeping track of private Fragment property in Activity so that I always have the same Fragment object throughout the activity's lifetime? Thanks!

2 Answers

setRetainInstance(true): The Fragment's state will be retained (and not destroyed!) across configuration changes (e.g. screen rotate). The state will be retained even if the configuration change causes the "parent" Activity to be destroyed. However, the view of the Fragment gets destroyed!

Lifecycle Calls:

  • onPause() -> onStop() -> onDestroyView() -> onDetach()
  • onAttach() -> onCreateView() -> onStart() -> onResume()

setRetainInstance(false): The Fragment's state will not be retained across configuration changes (default).

Lifecycle Calls:

  • onPause() -> onStop() -> onDestroyView() -> onDestroy() -> onDetach()
  • onAttach() -> onCreate() -> onCreateView() -> onStart() -> onResume()

Important: setRetainInstance(true) does not work with fragments on the back stack. setRetainInstance(true) is especially useful for long running operations inside Fragments which do not care about configuration changes.

1

If you mean a private property it means a property within the class so each time the activity is recreated a new instance with a new private fragment is created for Example at t=t1 the instance of Activity A is created so it contains all its private variables and in t=t2 a new instance of the Activity A is created and so when you set setRetainFragment(true)the Android framework under the hood retain your fragments without recreating them and preserves it state. You can refer to this link for further information Understanding Fragment's setRetainInstance(boolean)

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy