Starting Android 4.2, Android supports nested Fragments. The doc doesn't give a lot of explanations regarding nested Fragment
lifecycles but from experience, it appears their lifecycle is really similar to "regular" Fragments
.
It looks like there is one big difference though: child Fragments
are not restored when the parent Fragment
onCreate
method is called. As a consequence, it seems impossible to save/restore a reference to a particular Fragment
:
getChildFragmentManager.findFragmentByTag(String)
always returns null
in parent Fragment
onCreate(Bundle)
because mActive
is null
.putFragment
/getFragment
results in a NullPointerException
because getFragment
looks for the size of a null mActive
ArrayList
.So, my question is quite simple. Is there a correct way to retrieve a reference to a child Fragment
in the parent Fragment
onCreate
method?
I don't think you can in onCreate
as the view isn't constructed at that time. You can in onViewCreated()
though. The logic I used is:
onViewCreated()
, if there is, try to get the child fragmentBy "checking" I mean looking up the fragment by id. I guess by tag should work too.
AFAIK you can't get a child fragment before the view hierarchy is restored or created, but you could do the same at later time, for example in onActivityCreated()
What about setRetainInstanceState(true) on your fragment? Could it solve your problem? It solved some problems when I have ChildFragments in a Fragment. I only have to keep a reference to the childfragment in the fragment.
But I allways did that in onCreateView(). Not sure if it will work in onCreate()
Or do you mean something completely different?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With