Fragment 和 Fragment 之间的通讯

Fragment 的存在必须要要依附于Activity,FragmentActivity是继承Activity的。Fragment和Fragment之间的通讯的桥梁就是这个FragmentManager这个类,这个类是用来管理所有的这个Fragment的,所以我们能找到任何一个你所需要的Fragment类。所以,只要在提供一个公共方法,那么就可以在其他的Fragment中找到你需要的Fragment直接调用方法(这样就相当与对象直接调用方法而已,只是我们没有去new的形式而已),如下面的代码。


需要在LeftFragement中修改RightFragment中的TextView的值。

public class RightFragment extends Fragment{

     private TextView textView;
@Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle   savedInstanceState)                   {
View view = inflater.inflate(R.layout.fragment_right, null);
textView = (TextView)view.findViewById(R.id.tv_change);
return view;
}

public void changeText(String str){
textView.setText(str);
}
}

public class LeftFragment extends Fragment{
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_left, null);
        Button btn = (Button) view.findViewById(R.id.btn);
        btn.setOnClickListener(new OnClickListener() {
     @Override
     public void onClick(View v) {
        FragmentManager fm   = getActivity().getSupportFragmentManage r();
        RightFragment rightFragment = (RightFragment) fm.findFragmentById(R.id.fragment_text);                                 rightFragment.changeText("已经被改变....");
                 }
        });
       return view;
}
}

布局文件:
      xmlns:tools="http://schemas.android.com/tools"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      tools:context=".MainActivity"
      android:orientation="horizontal" >

    
            android:name="com.stu.fragment.LeftFragment"
            android:layout_width="0dp"
            android:layout_weight="2"
            android:layout_height="fill_parent"/>
      
      
    
            android:id="@+id/fragment_text"
            android:name="com.stu.fragment.RightFragment"
            android:layout_width="0dp"
            android:layout_weight="3"
            android:layout_height="fill_parent"/>

转自:http://blog.sina.com.cn/s/blog_aba86c0d0101fux8.html

补充:此方法通过测试,出现空指针异常。未找到原因,后改用Handler实现Fragment间通信。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值