2014-2-14

本篇文章翻译自Android官方的培训教程,我也是初学者,觉得官方的Training才是最好的学习材料,所以边学边翻译,有翻译不好的地方,请大家指正。

如果我们在开发过程中为了重用Fragment这个UI组件,那么我们应该把Fragment设计成是“自包含”、“模块化”组件,这种组件定义自己的布局和行为。一旦我们成功定义了这样的可重用的Fragment,我们就可以将他们与Activity进行关联,然后与整个Application进行整体的UI组装。

我们经常需要一个Fragment与另一个Fragment进行通信,比如点击一个Fragment,另外一个Fragment进行响应。所有的Fragment与Fragment之间的通信,都是由与他们绑定之间的Activity来完成,2个Fragment之间是不能进行直接通信的。

下面具体介绍Fragment直接的通信的步骤。

第一步:定义接口

为了首先实现Fragment与它所绑定的Activity直接进行通信,我们需要在Fragment的类中定义一个接口,并且在它所绑定的Activity的类中实现这个接口。Fragment通过在onAttach()这个生命周期回调函数中去捕获接口的实现,然后调用这个接口中的方法与Activity进行通信。

下面是一个例子:

public class HeadlinesFragment extends ListFragment {
OnHeadlineSelectedListener mCallback; // 容器Activity必须实现这个接口
public interface OnHeadlineSelectedListener {
public void onArticleSelected(int position);
} @Override
public void onAttach(Activity activity) {
super.onAttach(activity); // 这个确保容器Activity已经实现了这个回调接口,如果没有实现,会抛出异常
try {
mCallback = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
} ...
}

现在Fragment可以通过接口OnHeadlineSelectedListener的实例mCallbackinstance调用接口中的onArticleSelected()方法(或者接口中定义的其他的方法)发送messages到Activity。

例如,当用户点击一个list中的item,下面的Fragment中的方法会被调用。Fragment通过回调接口来发送事件到上层的Activity。

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Send the event to the host activity
mCallback.onArticleSelected(position);
}

第二步:实现接口 为了接收来自Fragment的回调事件,包含这个Fragment的Activity必须实现Fragment中所定义的接口。

例如,下面的代码就是上面接口的实现。

public static class MainActivity extends Activity
implements HeadlinesFragment.OnHeadlineSelectedListener{
... public void onArticleSelected(int position) {
// The user selected the headline of an article from the HeadlinesFragment
// Do something here to display that article
}
}

第三步:发送消息到Fragment

Activity通过调用findFragmentById()这个方法找到Fragment实例,然后直接调用这个实例的public方法。

比如,假设上述的activity可能包含另一个Fragment,这个Fragment用来显示前一个Fragment中具体item所对应的数据。在这个例子中,activity会将受到的数据,传送给这个Fragment,然后这个Fragment跟去该数据去显示相应的内容。

public static class MainActivity extends Activity
implements HeadlinesFragment.OnHeadlineSelectedListener{
... public void onArticleSelected(int position) {
// The user selected the headline of an article from the HeadlinesFragment
// Do something here to display that article ArticleFragment articleFrag = (ArticleFragment)
getSupportFragmentManager().findFragmentById(R.id.article_fragment); if (articleFrag != null) {
// If article frag is available, we're in two-pane layout... // Call a method in the ArticleFragment to update its content
articleFrag.updateArticleView(position);
} else {
// Otherwise, we're in the one-pane layout and must swap frags... // Create fragment and give it an argument for the selected article
ArticleFragment newFragment = new ArticleFragment();
Bundle args = new Bundle();
args.putInt(ArticleFragment.ARG_POSITION, position);
newFragment.setArguments(args); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); // Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null); // Commit the transaction
transaction.commit();
}
}
}

[转][译][Android基础]Android Fragment之间的通信的更多相关文章

  1. Android使用Fragment来实现ViewPager的功能(解决切换Fragment状态不保存)以及各个Fragment之间的通信

    以下内容为原创,转载请注明:http://www.cnblogs.com/tiantianbyconan/p/3364728.html 我前两天写过一篇博客<Android使用Fragment来 ...

  2. Android使用Fragment来实现TabHost的功能(解决切换Fragment状态不保存)以及各个Fragment之间的通信

    以下内容为原创,转载请注明:http://www.cnblogs.com/tiantianbyconan/p/3360938.html 如新浪微博下面的标签切换功能,我以前也写过一篇博文(http:/ ...

  3. Fragment的生命周期&同一Activity下不同Fragment之间的通信

    Android开发:碎片Fragment完全解析(2) Fragment的生命周期 和Activity一样,Fragment也有自己的生命周期,理解Fragment的生命周期非常重要,我们通过代码的方 ...

  4. Fragment之间的通信(四)

    自定义两个fragment的布局和java类. 在mainactivity中引用布局文件 在其中的一个fragment中的控件上添加监听,获取到另一个fragment中控件的内容,展示出来完成frag ...

  5. Android中使用开源框架EventBus3.0实现Fragment之间的通信交互

    1.概述 在之前的博文中简单介绍过如何实现fragment之间的信息交互:<Android中Fragment与Activity之间的交互(两种实现方式)>,今天继续给大家介绍一种可以实现此 ...

  6. Android - Fragment (三)不同Fragment之间的通信

    在Fragment的java文件中,可以使用getActivity()来获得调用它的activity, 然后再找到另一个Fragment,进行通信 getActivity().getFragmentM ...

  7. <Android基础>(四) Fragment Part 1

    Fragment 1)Fragment的简单用法 2)动态添加Fragment 3)在Fragment中模拟返回栈 4)Fragment和活动之间通信 第四章 Fragment Fragment是一种 ...

  8. Android Fragment之间的通信(用fragment替换掉XML布局文件中的一个线性布局)

    1.XML布局 (1)主界面 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xml ...

  9. <Android基础> (四) Fragment Part 2

    4.3 Fragment的生命周期 4.3.1 Fragment的状态和回调 1.运行状态 当一个Fragment是可见的,并且它关联的活动正处于运行状态是,该Fragment也处于运行状态 2.暂停 ...

随机推荐

  1. 【Git】git clone与git pull区别

    从字面意思也可以理解,都是往下拉代码,git clone是克隆,git pull 是拉.但是,也有区别: 从远程服务器克隆一个一模一样的版本库到本地,复制的是整个版本库,叫做clone.(clone是 ...

  2. Apache+jboss群集部署

    Jboss default方式上的Cluster配置[二] - 操作系统http://www.myexception.cn/operating-system/862858.html Jboss def ...

  3. 正排索引(forward index)与倒排索引(inverted index) (转)

    一.正排索引(前向索引) 正排索引也称为"前向索引".它是创建倒排索引的基础,具有以下字段. (1)LocalId字段(表中简称"Lid"):表示一个文档的局部 ...

  4. Codeforces 776C - Molly's Chemicals(思维+前缀和)

    题目大意:给出n个数(a1.....an),和一个数k,问有多少个区间的和等于k的幂 (1 ≤ n ≤ 10^5, 1 ≤ |k| ≤ 10, - 10^9 ≤ ai ≤ 10^9) 解题思路:首先, ...

  5. 结构体对齐及#pragma详细解释

    在linux下c语言结构体对齐: 1.自然对齐 struct 是一种复合数据类型,其构成元素既可以是基本数据类型(如int.long.float 等)的变量,也可以是一些复合数据类型(如array.s ...

  6. csu 最优对称路径(bfs+记忆化搜索)

    1106: 最优对称路径 Time Limit: 1 Sec  Memory Limit: 128 MBSubmit: 371  Solved: 77[Submit][Status][Web Boar ...

  7. [你必须知道的.NET]第十九回:对象创建始末(下)

    本文将介绍以下内容: 对象的创建过程 内存分配分析 内存布局研究 接上回[第十八回:对象创建始末(上)],继续对对象创建话题的讨论>>> 2.2 托管堆的内存分配机制 引用类型的实例 ...

  8. Zookeeper(二)Zookeeper原理与API应用

    一 Zookeeper概述 1.1 概述 Zookeeper是Google的Chubby一个开源的实现.它是一个针对大型分布式系统的可靠协调系统,提供的功能包括:配置维护.名字服务. 分布式同步.组服 ...

  9. WERTYU(UVa10082)

    C++ 11 代码如下: #include<iostream> using namespace std; const char s[] = { "`1234567890-=QWE ...

  10. [实战]MVC5+EF6+MySql企业网盘实战(5)——登录界面,头像等比例压缩

    写在前面 关于该项目,已经很久没更新了.实在是找不到一个好的ui,没办法就在网上找了一个还不错的,就凑合着先用着吧,先出第一版,以后的再想着去优化.最近更新与网盘项目相关的内容是准备在项目中使用一个美 ...