fragment内嵌fragment之间传值+切换fragment

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/cbjcry/article/details/84921347

跳转:

从一个Fragment跳转到另一个Fragment

android从fragment跳转到fragment问题解决

[Android]Fragment的四种跳转

 

传值:

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

嵌套Fragment的使用及常见错误

android 布局中Fragment嵌套Fragment

Android Support v4 支持包中 Fragment用法

 

使用activity的fragmenttransation的replace方法替换

private void changeToAnotherFragment(){
    //如果是用的v4的包,则用getActivity().getSuppoutFragmentManager();
    FragmentManager fm = getActivity().getFragmentManager();
	
    //注意v4包的配套使用
    Fragment fragment = new 目标fragment();
    fm.beginTransaction().replace(容器控件id,fragment).commit();
}

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

 

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

 

如图,在第二层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. 
   * 
   * <p>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); 

 ..

 

 

 

 

展开阅读全文

没有更多推荐了,返回首页