I am working on an app that has the following UI structure:
- One
Activity
, called FoodActivity- This
Activity
implements bottom navigation. Hence, can show three categories of food: fruit, meat and fish - The
Activity
has a bigFragment
container, where I attach theFragment
for fruit, meat and fish as the user interacts with the bottom tabs.
- This
- Each outer
Fragment
(fish, meat and fish) presents navigation betweenFragments
: it can show a list of fruits, and the the detail for the selected fruit.- Hence, the outer
Fragments
have anotherFragment
container in where I attachFragments
for the fruit list or fruit detail.
- Hence, the outer
So, it's one main Activity
, which has a big Fragment
container where I swap Fragments
, which in turn nest other Fragments
To switch from one outer Fragment
to another using the tabs (ie: switch from fruit to meat), I perform a Fragment Transaction in the outer Fragment
container:
private void switchFragment(Fragment fragment, String fragmentTag) {
final FragmentManager fm = getSupportFragmentManager();
final FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment_outer, fragment, fragmentTag);
ft.commit();
}
The problem is that when switching the first-level Fragments
, the state of their ChildFragmentManager
is not kept.
For example, imagine that:
- I start in FuitFragment
- The FruitFragment, when created, attaches the nested FruitListFragment
- The user navigates in the nested Fragment
container, from FruitListFragment to FruitDetailFragment
- The user switches to another tab
- The user switches back to the fruit tab
- The child `FragmentManager* of the FuitFragment does not automatically put FruitDetailFragment in the nested fragment container.
More specifically, when switching back to the outer Fragment
:
onCreate
is called, withsavedInstance
== nullonCreateView
is called, withsavedInstance
== null
Hence, as the outer Fragment
onCreate
method is called, and I cannot tell whether or not to attach the child Fragment
(as one usually does with Activities
).
Moreover if I don't attach it (using an instance variable to check if I'm switching back to it) the child Fragment
container will be just empty.
Experiments and notes
I have experimented that if I add the outer fragment transaction to the backstack when attaching it, when switching back to it,
onCreate
method is NOT called and the childFragmentManager
will remember and attach the fragment it had before. However, I cannot add it to the backstack as per Google's specifications on bottom navigation.Setting
setRetainInstace
to true does not make any effect.
So, what should I do for properly restoring the state of the child FragmentManager
?
Am I doing something wrong, or is it that everything around nested Fragments in Android is not well supported (or a bit broken) and I simply should not provide navigation using nested Fragments?