Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - retaining fragment?

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!

like image 877
user2062024 Avatar asked Aug 13 '17 20:08

user2062024


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.

like image 51
Prakhar1001 Avatar answered Sep 24 '22 06:09

Prakhar1001


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)

like image 32
Bachiri Taoufiq Abderrahman Avatar answered Sep 21 '22 06:09

Bachiri Taoufiq Abderrahman