Fragment间通信传递数据 Communicating with Other Fragments
2016-03-30 11:23
239 查看
需求:
一个Activity中显示两个Fragment,想要在FragmentA中点击某个按钮时,切换到FragmentB,同时把用户输入的数据传递到B中。
思路:
Fragment的显示与否决定权在Activity里,想要传递数据就得通过这个“媒婆”,两个Fragment不应该直接通信。
方法:(其实这里就是一个回调的概念。)
1。先在FragmentA中定义一个接口,例如:
2。 然后在A中创建一个OnRegisterSuccessListener接口的对象,在按钮的点击事件里调用对象的onRegisterSuccess方法,并传入数据phoneNumber;
3。哦差点忘了实例化这个对象,我们 需要重写onAttach方法,在Activity与Fragment绑定时实例化(抛出的那个异常是为了在Activity没有实现接口时给个提醒)
4。控制Fragment的Activity实现这个接口,并且实现回调方法:
5。在实现回调方法里将A传递过来的数据用Bundle传递到FragmentB中:
6。最后一步,在FragmentB中接收数据:
7。这样就实现了2个Fragemnt间的数据通信。
学习地址: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
相关文章推荐
- 我的第一次出国行
- TCP与UDP
- js内置对象
- 网络七层协议的形象说明
- Linux下php安装memcache扩展
- iOS自带的Social.framework 自带的社交分享SDK
- java多线程-join方法详解(附面试题)
- angular中 ng-if 指令中的ng-model等指令失效问题
- linux的启动流程
- utl_url.escape和utl_url.unescape
- mysql 使用命令行连接数据过程
- TCP协议的三次握手和四次挥手
- JS常用自定义方法
- java 类处理工具
- 删除多列同时重复数据
- datatables服务器加载数据,多语言
- Maven系列一pom.xml 配置详解
- 各国语言缩写-各国语言简称
- iOS点击button放大后缩小效果,类似QQ、微信选择图片时的特效。
- KAFKA分布式消息系统