Getting a reference to a child Fragment after the parent Fragment has been recreated

前端 未结 3 1275
有刺的猬
有刺的猬 2021-01-31 19:13

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 ap

3条回答
  •  遇见更好的自我
    2021-01-31 19:48

    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:

    • Check if there is saved state in onViewCreated(), if there is, try to get the child fragment
    • Then check if the child fragment is null, if it is, add it using the child fragment manager.

    By "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()

提交回复
热议问题