the docs on setRetainInstance say :
This can only be used with fragments not in the back stack.
so I started playing with it.
I have one Activity with adds first frag A
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.content, new PackageFragment());
ft.commit
then from this frag I run a method from parent Activity which adds frag B to backstack
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.content, new OrderFragment());
ft.addToBackStack(null);
ft.commit();
then I create log msg from onCreate,onDestroy,onSaveInstanceState,onActivityCreated…etc
I try two versions of this process. Rotating the device on each fragment.
- default
Everything is as expected. onCreate, onDestroy on fragments fire
- setRetainInstance(true)
Everything is as expected?. onCreate, onDestroy on fragments dont fire
and all seems to work while fragments are in the backstack.. so why the docs say I shouldnt use it?
What are the scenarios where I might get in trouble?
thanks
Updated answer:
When adding a
Fragmentto the back stack and passing aBundlein theFragmentfromonSaveInstanceState()toonCreateView()on configuration change. CallingsetRetainInstance(true)will set theBundleto null on configuration change.(I’m not sure a developer would actually attempt this since using
setRetainInstance(true)makesonSaveInstanceState()kind of redundant, but I didn’t see the behaviour documented in the API docs so I wrote up this answer).If both
addToBackStack()andsetRetainInstance(true)are called,setRetainInstance()partly alters theFragmentlifecycle method calls and parameter values on configuration changes, compared to calling onlyaddToBackStack().Specifically, in the test below, looking a differences between calling only
addToBackStack()and callingsetRetainInstance(true)as well, and seeing what happens on configuration change:Calling
addToBackStack()but notsetRetainInstance(true);onCreate()andonDestroy()are called.onSaveInstanceState()is received as a parameter inonCreateView().Calling both
addToBackStack()andsetRetainInstance(true):onCreate()andonDestroy()are not called. This is metioned in the API docs.onSaveInstanceState()is not received inonCreateView(). The passed-inBundleis null.A test with logged method calls and parameters tested for null:
In the
Activity:In the
Fragment:and
Test 1: Fragment lifecycle when
addToBackStack()is called , andsetRetainInstance(true)is not called[Device rotated from portrait to landscape]
Test 2 & 3: Fragment lifecycle calls with
setRetainInstance(true)called,addToBackStack()called / not called (same result):[Device rotated from portrait to landscape]