Android Fragment 和 Activity相互传值
16lz
2021-01-23
- Activity 给 Fragment传值
1.1 Activity中代码
//send data to fragment Bundle bundle = new Bundle(); bundle.putString("landId", landId); pictureDisplayFragment.setArguments(bundle);
1.2 Fragment 接受代码
Bundle bundle = getArguments(); String landId = bundle.getString("landId");
-
Fragment 给所附属的 Activity传值
2.1 首先在 fragment 中写回调接口和重写onAttach方法,并创建实例化
//实例化接口private CallBackValue mCallBackValue;//定义一个回调接口 public interface CallBackValue{ public void SendBundle(Bundle bundle); } //fragment 与 activity 通过onAttach() 方法回调,重写该方法即可@Override public void onAttach(Activity activity) { // TODO Auto-generated method stub super.onAttach(activity); //当前fragment从activity重写了回调接口得到接口的实例化对象 mCallBackValue = (CallBackValue) getActivity(); }
2.2 实现接口和回调后,Fragment 通过下面的代码向 Activity 传值。
Intent picPlayActivity = new Intent(getActivity(), PicturePlayActivity.class);Bundle bundle = new Bundle();bundle.putString("siteName","地块名");mCallBackValue.SendBundle(bundle );
2.3 Activity 中要继承 Fragment中实现的回调接口
implements CallBackValue
2.4 Activity 通过下面代码接受传值
@Override public void SendBundle(Bundle bundle) { //这里只是举例子,接收的参数的一般是外部变量 String string = bundle.getString("siteName"); }
至此,Fragment 给 Activity 传值就完成了。
-
Fragment 给另外的 Activity 传值
3.1 Fragment 中实现代码
Intent picPlayActivity = new Intent(getActivity(), PicturePlayActivity.class); Bundle toActivity = new Bundle(); toActivity.putString("siteName","地块名"); picPlayActivity.putExtras(toActivity); startActivity(picPlayActivity);
3.2 Activity 中接受值代码
Intent intent = getIntent(); Bundle bundle = intent.getExtras();String siteName = bundle.getString("siteName");
很简单就完成了。
更多相关文章
- Android JNI 实例: SimpleJNI
- Android 监听按钮点击事件的三种方式(1:匿名内部类;2:外部类;3:接口方
- Android代码总结,Sdcard和图片相关
- android 下载不了源代码?
- android 2.2 完全 退出 ---程序代码
- Android 功能代码总结