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!
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With