Possible to retain state of child fragment when navigating back from another activity?

846 views Asked by At

I have an activity that hosts a fragment A.

When fragment A is attached, I add a child Fragment B or C (depending on some flag) to a container in the A fragment.

Now if I navigate forward to a new activity and then hit the back button, the fragment A state is retained perfectly but the child fragments are not retained and there is a brief pause before they are reattached.

The two child fragments also each hold listviews so ideally I would want to retain them and keep their scroll position when navigation back. Is this possible? I tried setretaininstance(true) on the child fragments but that throws an exception.

some code:

 Fragment fluidLayoutFragment = FluidLayoutFragment.newInstance(userId);
 FragmentTransaction ft = getChildFragmentManager().beginTransaction();
 fluidLayoutFragment.setTargetFragment(this, 0);
 ft.replace(R.id.layout_container, fluidLayoutFragment).commit();
2

There are 2 answers

2
Mike On

Without looking at your code could it be that you need to use getChildFragmentManager() instead of getFragmentManager()?

From the documentation: http://developer.android.com/reference/android/app/Fragment.html#getChildFragmentManager()

Return a private FragmentManager for placing and managing Fragments inside of this Fragment.

0
pat On

After reading Mike's comment, I was using a child fragment manager but when I switched it to a normal fragment manager it seems to work now. Seems like odd behavior but all good now.