前言
Activity 与 Fragment 的使用在Android开发中非常多
今天,我将主要讲解 Activity 与 Fragment 如何进行通信,实际上是要解决两个问题:
Activity 如何传递数据到 Fragment?
Fragment如何传递数据到Activity ?
下面,我将解答这两个问题。

阅读本文前,建议阅读Android:Fragment最全面介绍 & 使用方法解析

问题1: Activity 如何传递数据到 Fragment?
答:采用 Bundle方式。具体Demo步骤如下:

步骤1:Activity的布局文件

activcity_2_fragment.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"> <TextView
android:id="@+id/text"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:text="我是Activity" /> <FrameLayout
android:layout_below="@+id/button"
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="500dp"/>
</LinearLayout>

  

步骤2:设置 Fragment的布局文件
fragment.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorAccent"
> <TextView
android:id="@+id/fragment"
android:text="我是fragment"
android:layout_gravity="center"
android:textSize="30dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/> <TextView
android:id="@+id/text"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:text="等待Activity发送消息" /> <Button
android:id="@+id/button"
android:layout_gravity="center"
android:text="点击接收Activity消息"
android:layout_centerInParent="true"
android:textSize="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>

  

步骤3:设置Activity的类文件
Activity2Fragment

public class Activity2Fragment extends AppCompatActivity {

TextView text;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activcity_2_fragment); text = (TextView) findViewById(R.id.text); // 步骤1:获取FragmentManager
FragmentManager fragmentManager = getFragmentManager(); // 步骤2:获取FragmentTransaction
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); // 步骤3:创建需要添加的Fragment
final mFragment fragment = new mFragment(); // 步骤4:创建Bundle对象
// 作用:存储数据,并传递到Fragment中
Bundle bundle = new Bundle(); // 步骤5:往bundle中添加数据
bundle.putString("message", "I love Google"); // 步骤6:把数据设置到Fragment中
fragment.setArguments(bundle); // 步骤7:动态添加fragment
// 即将创建的fragment添加到Activity布局文件中定义的占位符中(FrameLayout)
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit(); }
}

  

步骤4:设置Fragment的类文件
mFragment.java

public class mFragment extends Fragment {
Button button;
TextView text;
Bundle bundle;
String message; @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View contentView = inflater.inflate(R.layout.fragment, container, false);
// 设置布局文件 button = (Button) contentView.findViewById(R.id.button);
text = (TextView) contentView.findViewById(R.id.text); // 步骤1:通过getArgments()获取从Activity传过来的全部值
bundle = this.getArguments(); // 步骤2:获取某一值
message = bundle.getString("message"); // 步骤3:设置按钮,将设置的值显示出来
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { // 显示传递过来的值
text.setText(message); }
}); return contentView;
}
}

  

展示结果

至此,Activity 传递数据到 Fragment 讲解完毕。

问题2:Fragment 如何传递数据到 Activity
答:采用 接口回调 方式。
接口回调 回顾
把实现了某一接口的类所创建的对象的引用 赋给 该接口声明的变量,通过该接口变量 调用 该实现类对象的实现的接口方法。

// 接口声明的变量
Com com; // 实现了Com接口的类(Com1)所创建的对象的引用 赋给 该接口声明的变量
Com com = new Com1; // 通过该接口变量(com) 调用 该实现类对象(Com1)的实现的接口方法(carson())
com.carson();

  

具体Demo
步骤1:在Activity的布局文件定义1占位符(FrameLayout)
activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="scut.carson_ho.fragment_2_activity.MainActivity"> <TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:text="等待Fragment发送消息" /> <Button
android:id="@+id/button"
android:layout_below="@+id/text"
android:text="点击接收Fragment消息"
android:layout_centerInParent="true"
android:textSize="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" /> <FrameLayout
android:layout_below="@+id/button"
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="500dp"/> </RelativeLayout>

  

步骤2:设置Fragment的布局文件
fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
> <TextView
android:id="@+id/fragment"
android:text="我是fragment"
android:gravity="center"
android:textSize="30dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorAccent"/> </LinearLayout>

  

步骤3:设置回调接口
该接口用于用于Activity与Fragment通信
ICallBack.java

public interface ICallBack {
void get_message_from_Fragment(String string); }

  

步骤4:设置Fragment的类文件
mFragment.java

public class mFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View contentView = inflater.inflate(R.layout.fragment, container, false);
// 设置布局文件
return contentView;
} // 设置 接口回调 方法
public void sendMessage(ICallBack callBack){ callBack.get_message_from_Fragment("消息:我来自Fragment"); }
} View text; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); button = (Button)findViewById(R.id.button);
text = (TextView)findViewById(R.id.text); // 步骤1:获取FragmentManager
FragmentManager fragmentManager = getFragmentManager(); // 步骤2:获取FragmentTransaction
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); // 步骤3:创建需要添加的Fragment
final mFragment fragment = new mFragment(); // 步骤4:动态添加fragment
// 即将创建的fragment添加到Activity布局文件中定义的占位符中(FrameLayout)
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit(); button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { // 通过接口回调将消息从fragment发送到Activity
fragment.sendMessage(new ICallBack() {
@Override
public void get_message_from_Fragment(String string) {
text.setText(string);
}
}); }
});
} }

  

结果展示

至此,将数据从 Fragment 发送到 Activity 讲解完毕

总结
看完本文,你应该非常清楚该如何实现 Activity 与 Fragment 相互通信

下一篇文章我将对讲解Android 的相关知识,有兴趣可以继续关注Carson_Ho的安卓开发笔记
---------------------
作者:Carson_Ho
来源:CSDN
原文:https://blog.csdn.net/carson_ho/article/details/75453770
版权声明:本文为博主原创文章,转载请附上博文链接!

Android:手把手教你 实现Activity 与 Fragment 相互通信,发送字符串信息(含Demo)的更多相关文章

  1. Android:手把手教你打造可缩放移动的ImageView(下)

    在上一篇Android:手把手教你打造可缩放移动的ImageView最后提出了一个注意点:当自定义的MatrixImageView如ViewPager.ListView等带有滑动效果的ViewGrou ...

  2. 【转载】Android开发中巧用Activity和Fragment

    1.Activity的生命周期 1)多个Activity组成Activity栈,当前活动位于栈顶.我们先来看看各种Activity基类的类图: 当Activity类定义出来之后,这个Activity何 ...

  3. android 手把手教您自定义ViewGroup(一)

    1.概述 在写代码之前,我必须得问几个问题: 1.ViewGroup的职责是啥? ViewGroup相当于一个放置View的容器,并且我们在写布局xml的时候,会告诉容器(凡是以layout为开头的属 ...

  4. Android:手把手教你打造可缩放移动的ImageView(上)

    定义ImageView,实现功能如下: 1.初始化时图片垂直居中显示,拉伸图片宽度至ImageView宽度. 2.使用两根手指放大缩小图片,可设置最大放大倍数,当图片小于ImageView宽度时,在手 ...

  5. Fragment与Activity之间的相互通信

    https://blog.csdn.net/u012702547/article/details/49786417 https://blog.csdn.net/carson_ho/article/de ...

  6. 新人补钙系列教程之:AS 与 JS 相互通信

    比较常用的,AS 调用 JS private function callJS():void{ ExternalInterface.addCallback("callbackQQPay&quo ...

  7. Android开发之手把手教你写ButterKnife框架(三)

    欢迎转载,转载请标明出处: http://blog.csdn.net/johnny901114/article/details/52672188 本文出自:[余志强的博客] 一.概述 上一篇博客讲了, ...

  8. 【转】手把手教你读取Android版微信和手Q的聊天记录(仅作技术研究学习)

    1.引言 特别说明:本文内容仅用于即时通讯技术研究和学习之用,请勿用于非法用途.如本文内容有不妥之处,请联系JackJiang进行处理!   我司有关部门为了获取黑产群的动态,有同事潜伏在大量的黑产群 ...

  9. 手把手教你读取Android版微信和手Q的聊天记录(仅作技术研究学习)

    1.引言 特别说明:本文内容仅用于即时通讯技术研究和学习之用,请勿用于非法用途.如本文内容有不妥之处,请联系JackJiang进行处理!   我司有关部门为了获取黑产群的动态,有同事潜伏在大量的黑产群 ...

随机推荐

  1. app优化篇

    UIImageView高效加个圆角 一般通过clipsToBounds和layer.cornerRadius会强制Core Animation提前渲染屏幕的离屏绘制,影响性能. 通过贝塞尔曲线切割图片 ...

  2. mysql报错Ignoring the redo log due to missing MLOG_CHECKPOINT between

    mysql报错Ignoring the redo log due to missing MLOG_CHECKPOINT between mysql版本:5.7.19 系统版本:centos7.3 由于 ...

  3. web状态管理机制

    引入:b/s(浏览器/服务器模式)区别于winform的是winform中只加载一次页面构造函数,而b/s中只要点击按钮或者其他涉及后台的操作都会调用后台代码.一般情况下为了防止服务器过载,b/s不会 ...

  4. 以选项卡的故事扯扯js面向对象

    在现在的网页中,选项卡(我自己这样子叫)是非常普遍的,也是比较基础,学了原型实现选项卡也挺久了,最近在学ES6,学了用类实现选项卡,今天就在此做个总结,别的废话也不多说. 以"貌" ...

  5. Gis数据处理2 ---8.18

    1空间参考: 了解大地水准面,参考椭球体,基准面的概念 以及之间的关系   基准面描述的是参考椭球体中心 跟地心的关系   我们常说的北京54.西安80.CGCS2000,实际上指的是我国的三个大地基 ...

  6. 18 os/os.path模块中关于文件/目录常用的函数使用方法 (转)

    os模块中关于文件/目录常用的函数使用方法 函数名 使用方法 getcwd() 返回当前工作目录 chdir(path) 改变工作目录 listdir(path='.') 列举指定目录中的文件名('. ...

  7. 解决CUDA driver version is insufficient for CUDA runtime version

    问题 在服务器上安装mxne的GPU版本 sudo pip install mxnet-cu80==1.2.1 然后在gpu上创建数据 import mxnet as mx mx.nd.array([ ...

  8. 裸奔的bootloader单步调试

    2011-03-01 23:25:22 目地:更清晰的了解bootloader的结构及功能.为移植U-boot打基础. 以前只知道大概,今天利用IAR调试工具,看着汇编代码,看着寄存器,看着内存.来单 ...

  9. rangeOfString 和 containsString 兼容iOS7处理

    //查找字符串是否包含"心" NSString *str = @"每天都有好心情"; if ([str containsString:@"心" ...

  10. phpstorm 配置git上传代码到 码云

    方法一: 1.安装git,一路next下去. git安装完自带右键菜单 2.看一下phpstorm里的路径是否正确. 3.使用phpstorm管理代码库 新建,从码云上已有的公开项目克隆一份到本地: ...