getSupportFragmentManager().findFragmentById()返回为null

来源:互联网 发布:电视连网络怎么看电视 编辑:程序博客网 时间:2024/05/20 02:21


之前开发过程中,从来没有在布局中直接使用过fragment,一般都是在布局中使用FrameLayout,然后在activity中给这个布局设置

fragment,在新项目中遇到了这样的使用:


[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <fragment    android:id="@+id/fragment"    android:name="com.onlydoone.busposition.fragment.monitor.util.CycleViewPager"    android:layout_width="match_parent"    android:layout_height="170dp"></fragment> 

原来使用的是,要得到这个fragment,使用的是

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. cycleViewPager = (CycleViewPager) getFragmentManager().findFragmentById(R.id.fragment);

但这个方法,低版本没问题,但高版本就会获取不到,返回null,最后,百度了好久,才找到答案,如果你的fragment是fragment中嵌套Fragment,想在代码中获取它的实例,应该这样写:


[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. cycleViewPager = (CycleViewPager) getChildFragmentManager().findFragmentById(R.id.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()了。


0 0
原创粉丝点击