Fragment间通信传递数据 Communicating with Other Fragments

需求:
一个Activity中显示两个Fragment,想要在FragmentA中点击某个按钮时,切换到FragmentB,同时把用户输入的数据传递到B中。

思路:
Fragment的显示与否决定权在Activity里,想要传递数据就得通过这个“媒婆”,两个Fragment不应该直接通信。

方法:(其实这里就是一个回调的概念。)

1。先在FragmentA中定义一个接口,例如:

    /**
     * 注册成功后回调,用于传递数据至登录
     */
    public interface OnRegisterSuccessListener {
        void onRegisterSuccess(String phoneNumber);
    }

2。 然后在A中创建一个OnRegisterSuccessListener接口的对象,在按钮的点击事件里调用对象的onRegisterSuccess方法,并传入数据phoneNumber;

    if (status == 0) {
        registerResult = "注册成功!";
                              mOnRegisterSuccessListener.onRegisterSuccess(phoneNumber);
                }

3。哦差点忘了实例化这个对象,我们 需要重写onAttach方法,在Activity与Fragment绑定时实例化(抛出的那个异常是为了在Activity没有实现接口时给个提醒)

 @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mOnRegisterSuccessListener = (OnRegisterSuccessListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                + "must implement OnRegisterSuccessListener!");
        }

    }

4。控制Fragment的Activity实现这个接口,并且实现回调方法:

public class LoginActivity extends Activity implements RegFragment.OnRegisterSuccessListener

5。在实现回调方法里将A传递过来的数据用Bundle传递到FragmentB中:

@Override
    public void onRegisterSuccess(String phoneNumber) {
        LogFragment logFragment = new LogFragment();
        Bundle bundle = new Bundle();
        bundle.putString("phoneNumber",phoneNumber);
        logFragment.setArguments(bundle);

        getFragmentManager().beginTransaction().replace(R.id.container, logFragment).commit();
    }

6。最后一步,在FragmentB中接收数据:

 Bundle bundle = getArguments();
        if (bundle != null){
            String phoneNumber = bundle.getString("phoneNumber");
            if (!TextUtils.isEmpty(phoneNumber)) {
                etNumber.setText(phoneNumber);
            }
        }else {
            LogUtils.e(TAG,"Bundle is null !");
        }

7。这样就实现了2个Fragemnt间的数据通信。

学习地址:Communicating with Other Fragments

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

拭心

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值