Nested fragments not retained in latest support library releases
Since version 17 of the Android API it has been possible to nest fragments within your applications. Using the support library that the Android team provide, you can utilize this functionality from version 11 onwards.
There is however a bemusing issue in the latest versions of the support library which mean that nested fragments dont function as one would expect.
As outlined in this issue, versions 20 and 21 of the support library do not retain nested fragments correctly on configuration changes. This can be quite a difficult issue to diagnose if you are not expecting it (which you shouldn't be). I stumbled upon it because a nested map was disappearing on orientation change.
A duplicate issue more explicitly states the cause: "The issue is that Fragments now always null out their mChildFragmentManager property, so when they are re-attached to an Activity, a new child FragmentManager is always created, thus losing the old nested Fragments."
I wanted to see for myself so had a look at the source where you can see that the
mChildFragmentManager is set to null.
Within the comments on the issue there is a link which proposes a solution.
The proposed solution is not however particularly clean or clear. As such I have created a gist with the solution I am using.
It works as follows:
The first time we load a fragment that extends from this base class, we save a reference to the child fragment manager.
On orientation change the saved instance variable is retained.
When the fragment is reattached post orientation change, if the variable is non null we use reflection to assign its value to the property which the support library uses.
I find it really quite bemusing that the Android team have not commented on this.. an issue that has been present for 8 months. I am also suprised that so few people have had anything to say on the matter.
It should be noted that this fix isn't guaranteed to continue to work. Hopefully Google will fix this in the next support library release but if they don't it is theoretically possible that they could change the variable name used for the child fragment manager (although extremely unlikely).
Reflection is less than ideal but the methods we would need to override/the variables we need to access to fix this any other way are package private so this is the best we will get for now.
Thanks of course to all who have commented on/investigated the issue. Hopefully this post provides a little more exposure for anyone else experiencing it and looking for a solution.