activity嵌套fragment,fragment内嵌fragment之间传值切换fragment

至于fragment的用法,fragment+viewpager的滑动切换代码请参考博文

Android基础:翻页控件Viewpager的使用方法,viewpager+fragment混合使用

fragment与Activity


当在使用activity嵌套fragment,fragment再嵌套子fragment时,相当于有两层fragment,假设最外层为第一层,其中一个Fragment为ParentfragmentA,该ParentFragmentA中又嵌套了三个fragment,也就是说第二层为ChildFragment1,ChildFragment2,ChildFragment3,如果想在其中一个子fragment中的控件点击切换到同一层的另一个子fragment

activity嵌套fragment,fragment内嵌fragment之间传值切换fragment_第1张图片

如图,在第二层fragment中,child1fragment中有两个控件viewI和viewII,点击viewI可以切换到同一层的fragment,比如,点击切换到ChildFragment2

实现如下:

在点击viewI时进行如下操作

  FragmentManager manager = getFragmentManager();//获取到父fragment的管理器
  //获取到父parentFragment
  ParentFragmentA home = (ParentFragmentA) manager.getFragments().get(0);
 //获取到ParentFragment的mViewPager变量      
  home.mViewPager.setCurrentItem(1);
说明一下,ParentFragmentA中声明的mViewPager必须为public。

说一下getFragmentManger方法


  /**
     * Return the FragmentManager for interacting with fragments associated
     * with this fragment's activity.  Note that this will be non-null slightly
     * before {@link #getActivity()}, during the time from when the fragment is
     * placed in a {@link FragmentTransaction} until it is committed and
     * attached to its activity.
     *
     * 

If this Fragment is a child of another Fragment, the FragmentManager * returned here will be the parent's {@link #getChildFragmentManager()}. */ final public FragmentManager getFragmentManager() { return mFragmentManager; } /** * Return a private FragmentManager for placing and managing Fragments * inside of this Fragment. */ final public FragmentManager getChildFragmentManager() {


官方API已经写明,getFragmentManger方法:如果该fragment是另一个fragment的子fragment,则获取到的是父fragment的manager

getChildFragmentManager方法:获取到外层fragment的子fragment的manager


对于viewII的点击事件,实现从Child1切换到ParentB

              //获取到 所依附的activity对象
                InitEmptyKeyActivity activity  = (InitEmptyKeyActivity) getActivity();
               activity.mViewPager.setCurrentItem(IntentConstant.MANAGE_AND_OP_FRAGMENT);










你可能感兴趣的:(Android拓展学习)