题记

—— 执剑天涯,从你的点滴积累开始,所及之处,必精益求精。


ActivityFragment 之间进行数据传递是,在Activity中将要传递的数据封装在 Bundle中,然后在 Activity 中使用 Fragment 的实例通过 setArgument(Bundel bundel) 方法绑定传递,在要传递到的Fragment中 使用this.getArgment(),得到传递到的Bundle,从而获取到传递。

github? 本文章涉及的测试源码 百度同步
CSDN 网易云课堂教程 掘金
知乎 Flutter系列文章 头条同步

1 Activity 向 Fragment 中传递参数

1.1 写法一

如下代码清单 1-1 在 Activity 中创建 TestAFragment 然后绑定 Bundle 数据,然后 commit 显示 TestAFragment 。

//代码清单 1-1
//传递数据
private void sendTestFunction() {//创建 Fragment 实例TestAFragment fragment = new TestAFragment();//构建 BundleBundle bundle = new Bundle();//设置数据bundle.putString("title", "传递到的数据");//绑定 Fragmentfragment.setArguments(bundle);FragmentManager fragmentManager = getSupportFragmentManager();FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();fragmentTransaction.replace(R.id.framelayout, fragment);fragmentTransaction.commit();}

然后在 TestAFragment 中获取 Bundle 从而获取数据如下代码清单 1-2 所示:

//代码清单 1-2
public class TestAFragment extends Fragment {public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {/// Fragment 所使用的 View View view = inflater.inflate(R.layout.fragment_first, container, false);///一个文本 组件 TextView textView = (TextView) view.findViewById(R.id.tv_firster_content);//获取Bundle 然后获取数据Bundle bundle = this.getArguments();//得到从Activity传来的数据String title = null;if (bundle != null) {title = bundle.getString("title");}///设置显示数据 textView.setText(title);return view;}}
1.2 写法二

通过 fragment 的静态方法来创建实例并绑定数据 ,如下代码清单 1-3 在 Activity 中 :

//代码清单 1-3
//传递数据
private void sendTestBFunction() {//创建 Fragment 实例// 通过静态方法来创建并绑定数据 TestBFragment fragment = TestBFragment.newInstance("测试数据");FragmentManager fragmentManager = getSupportFragmentManager();FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();fragmentTransaction.replace(R.id.framelayout, fragment);fragmentTransaction.commit();}

然后对应的 TestBFragment 中声明如下代码清单 1-4所示 :

//代码清单 1-3
public class TestBFragment extends Fragment {/*** @param title 参数* @return  Fragment 实例*/public static TestBFragment newInstance(String title) {//创建 Fragment 实例TestBFragment fragment = new TestBFragment();//创建 BundleBundle lBundle = new Bundle();lBundle.putString("title", title);fragment.setArguments(lBundle);return fragment;}public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {View view = inflater.inflate(R.layout.fragment_first,container,false);TextView textView = (TextView)view.findViewById(R.id.tv_firster_content);//获取Bundle 然后获取数据Bundle bundle =this.getArguments();//得到从Activity传来的数据String title = null;if(bundle!=null){title = bundle.getString("title");}textView.setText(title);return view;}}

需要注意的是静态方法 newInstance 只是用来创建 Fragment 实例与设置绑定数据的,如果需要在 Fragment 中使用还需要通过 Bundle 执行获取操作。

2 Fragment 向 Activity 中传递参数

Fragment 是在 Activity 中加载,数据传递思路就是 Activity 中设置监听 ,然后 Fragment 发送回调消息就可以 。

首先定义 监听 如下代码清单 2-1 所示 :

//代码清单 2-1
public  interface FragmentCallBack {//定义监听方法 根据实际需求来void test(int flag);
}

然后为 Activity 绑定监听,如下代码清单 2-2 所示:

///代码清单 2-2
public class MainActivity extends AppCompatActivity  implements FragmentCallBack{/// Fragment 消息回调的方法@Overridepublic void test(int flag) {}... ...
}

然后在 Fragment 中 获取这个 监听并发送回调 ,如下代码清单 2-3所示:

//代码清单 1-3
public class TestBFragment extends Fragment {//监听回调FragmentCallBack mFragmentCallBack;///onAttach 当 Fragment 与 Activity 绑定时调用 @Overridepublic void onAttach(Context context) {super.onAttach(context);///获取绑定的监听 if (context instanceof FragmentCallBack) {mFragmentCallBack = (FragmentCallBack) context;} }///onDetach 当 Fragment 与 Activity 解除绑定时调用 @Overridepublic void onDetach() {super.onDetach();mFragmentCallBack = null;}...
}

然后在业务代码中,如点击按钮传递数据给 Activity :

///消息回调到 Activity
if (mFragmentCallBack != null) {mFragmentCallBack.test(111);
}

3 聊聊 Bundle

Bundle主要用于传递数据;它保存的数据,是以key-value(键值对)的形式存在的,是一个信息的载体,内部其实就是维护了一个Map<String,Object>。

需要注意的是 Intent 负责 Activity 之间的交互,内部是持有一个Bundle。

传递的数据可以是boolean、byte、int、long、float、double、String等基本类型或它们对应的数组,也可以是对象或对象数组,当Bundle传递的是对象或对象数组时,必须实现Serializable或Parcelable接口 。

Bundle提供了各种常用类型的putXxx()/getXxx()方法,用于读写数据,如下:

3.1 Activity

在activity间传递信息

Bundle bundle = new Bundle();        //创建bundle对象
bundle.putString("title", "张三"); //(String型)
bundle.putInt("age", 175);        //int 类型,value-175
intent.putExtras(bundle);        //通过intent绑定Bundle  startActivity(intent);

activity 中读取数据

//读取intent的数据给bundle对象
Bundle bundle = this.getIntent().getExtras();
//通过key得到value
String title = bundle.getString("title");
int age = bundle.getInt("age");
3.1 线程间传递

通过Handler将带有Bundle数据的message放入消息队列,其他线程就可以从队列中得到数据,代码如下:

//创建 Message对象
Message message=new Message();
//标记
message.what = 110;
//创建Bundle对象
Bundle bundle = new Bundle();  //设置数据
bundle.putString("text1","String 文本数据 ");
bundle.putInt("text2",1111);
///绑定 Message
message.setData(bundle);//Handler将消息放入消息队列
mHandler.sendMessage(message);

读取数据 ,在 Handler 的 handleMessage(Message msg) 方法回调用

String str1=msg.getData().getString("text1");
int int1=msg.getData().getString("text2");

本公众号会首发系列专题文章,付费的视频课程会在公众号中免费刊登,在你上下班的路上或者是睡觉前的一刻,本公众号都是你浏览知识干货的一个小选择,收藏不如行动,在那一刻,公众号会提示你该学习了。

Android Activity与Fragment之间的传值概述相关推荐

  1. android fragment传递数据,Android 两个Fragment之间传递数据实例详解

    Android 两个Fragment之间如何传递数据 FragmentA启动FragmentB,做一些选择操作后,返回FragmentA,需要把FragmentB里面选择的数据传回来.有什么办法? F ...

  2. 多个Activity与Fragment之间的数据传递

    多个Activity与Fragment之间数据传递 问题描述 解决思路 具体解决 bug de到亲妈落泪. 问题描述 首先展示个人问题的整体框架: ActivityA:主页面,有一个PageView控 ...

  3. 外部Activity和fragment之间的切换,传值

    下,Activity A /*下6h,*//*传值*//*跳转到Activity的Fragment中*/ Intent intent = new Intent(); intent.putExtra(& ...

  4. 老式Android中碎片Fragment之间的跳转和数据传递

    随着jetpack组件的使用,fragment之间的跳转和传值已经有相应的demo了.但是有时候难免不用Navigation,或者一些老项目的维护.这里,简单记录下老式fragment怎么跳转和传值. ...

  5. activity改成fragment android,Activity转换为Fragment

    Activity中加载不同的fragment  / Fragment中加载不同的fragment 主Activity中加载(切换)多个fragment(也可以理解为activity 尽管Fragmen ...

  6. 同一个 Activity 中 fragment 之间的跳转处理

    这里我们有两种方法: 方法一: 直接在 Fragment 中获取托管它的 activity 中的 FragmentManager,然后直接提交事务进行替换: // AFragment.java (这里 ...

  7. Android Activity和Fragment的转场动画

    Activity转场动画 Activity的转场动画是通过overridePendingTransition(int enterAnim, int exitAnim)实现的. 这个方法是API Lev ...

  8. 如何优雅的在 Activity、Fragment 之间传递参数

    前言 对于 Kotlin 早就有所耳闻,而且 Google 粑粑也大力推行 Kotlin 了,作为一个 Android coder 还是要紧跟粑粑的步伐的.恰巧遇上公司项目大改版,于是就决定将 Jav ...

  9. 用Broadcast广播在activity之间、fragment之间、activity和fragment之间相互传数据

    例如:A界面要收到B界面的更变信息 一.A界面注册广播 private static final String INTENT_BROADCAST = "android.intent.acti ...

最新文章

  1. Python计算大文件行数方法及性能比较
  2. tf13: 简单聊天机器人
  3. boost::unique_copy相关的测试程序
  4. Flex与.NET互操作(七):了解FluorineFx的环境配置(远程对象、网关、通道、目的地)...
  5. 浅谈 EF CORE 迁移和实例化的几种方式
  6. 程序员的算法课(10)-字符串排序算法实例(纯代码)
  7. OpenShift 4 - 在控制台中安装使用 Web Terminal
  8. CCF201809-2 买菜(100分)【序列处理+差分】
  9. AI独角兽商汤科技的内部服务容器化历程
  10. 天使和恶魔差异只在一念之间
  11. 【windows】修复win7便签
  12. Linux LAMP架构介绍及配置
  13. Windows重新生成UEFI引导,解决Windows蓝屏\BCD 0xc0000098
  14. 关于多目标跟踪的一点理解
  15. 2011 9 11最新过QQ游戏检测Cheat Engine(CE)搜索数据
  16. 苹果待处理订单要多久_苹果官网准备发货到发货要多久呀?
  17. android app wifi密码,无广告查看wifi密码的软件-WiFi密码查看清爽版app下载V999安卓版-西西软件下载...
  18. kaid mfc特征
  19. java期末考试复习题_JAVA期末考试复习试题
  20. 华为的鸿蒙系统是海思_华为鸿蒙系统能成为超算系统吗?华为硬件可以组成生态圈,可行!...

热门文章

  1. ICCV 2019 | 旷视研究院提出行人搜索当前最佳新方法
  2. 程序员都喜欢抄袭“代码”,而且还拿着高薪?难道就这么无法无天
  3. 全新思路!阿里达摩院将Transformer引入在线行为检测!ICCV2021
  4. Github | 商汤出品-可在视频里追踪单个对象PySOT
  5. Python中append()和extend方法的使用和区别
  6. 深度学习(十五)基于级联卷积神经网络的人脸特征点定位
  7. 二维vector容器读取txt坐标
  8. android 3d模型ppt,PPT已支持3D PPT怎么插入3D模型?
  9. 自动轨迹绘制的python代码_python 自动轨迹绘制的实例代码
  10. asp.net findcontrol html控件,c# – FindControl找不到控件