您的位置:首页 > 其它

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

2016-03-30 11:23 239 查看
需求:

一个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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: