getFragmentManager与getChildFragmentManager,解决fragment白屏

getFragmentManager到的是activity对所包含fragment的Manager,而如果是fragment嵌套fragment,那么就需要利用getChildFragmentManager()了。
getFragmentManager到的是activity对所包含fragment的Manager,而如果是fragment嵌套fragment,那么就需要利用getChildFragmentManager()了。
在使用fragment时 遇到
getFragmentManager()和getChildFragmentManager()的使用,
getFragmentManager()是所在fragment 父容器的碎片管理,
getChildFragmentManager()是在fragment 里面子容器的碎片管理。

getFragmentManager到的是activity对所包含fragment的Manager,而如果是fragment嵌套fragment,那么就需要利用getChildFragmentManager()了。

Fragment嵌套Fragment要用getChildFragmentManager。

 

遇到一个问题,Fragment放ViewPager,ViewPager里面是fragment。第一次进入没问题,再次进入ViewPager的fragment时里面内容就没了,数据丢失。

用的FragmentPagerAdapter.打Log发现FragmentPagerAdapter的getItem也不会调用,一直找不出原因。翻网上的回复终于找到答案。

本来里面的fragment用的还是getFragmentManager,Fragment嵌套Fragment时,里面要用getChildFragmentManager。

FragmentManager childFragmentManager = getChildFragmentManager();
ViewPager_Adapter viewPager_adapter = new ViewPager_Adapter(childFragmentManager, fragments); //FragmentPagerAdapter

 

The definition of getChildFragmentManager() is:

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

Meanwhile the definition of getFragmentManager() (or in this case getSupportFragmentManager()) is:

Return the FragmentManager for interacting with fragments associated with this fragment's activity.

Basically, the difference is that Fragment's now have their own internal FragmentManager that can handle Fragments. The child FragmentManager is the one that handles Fragments contained within only the Fragment that it was added to. The other FragmentManager is contained within the entire Activity.

In this case, what I'm guessing is you've added the Fragments to the Activity's FragmentManager. You get the child FragmentManager which doesn't contain what you are looking for. Thus you get the exception because it can't find the Fragment with the given ID because it's in a different FragmentManager.

 也就是说child FragmentManager是对你应用的那个Fragment的,而FragmentManager是包含在activity中的,所以有可能出现找不到对应的fragment片段的情况而显示空白。

=============================================

mSectionsPagerAdapter = new SectionsPagerAdapter(getActivity().getSupportFragmentManager());

在Fragment里面嵌套Fragment 的话,不要用上面的那句。。。会在ViewPager中出现。有些Fragment 不会加载的情况。。。既ViewPager 加载 Fragment 空白页的情况。。。。

所以   Fragment里面嵌套Fragment 的话:一定要用getChildFragmentManager();

  mSectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager());

转载于:https://www.cnblogs.com/lwhp/p/5760330.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值