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远程操作详解【转】

    转自:http://www.ruanyifeng.com/blog/2014/06/git_remote.html 作者: 阮一峰 日期: 2014年6月12日 Git是目前最流行的版本管理系统,学会 ...

  2. tracert和traceroute使用

    Traceroute提取发 ICMP TTL到期消息设备的IP地址并作域名解析.每次 ,Traceroute都打印出一系列数据,包括所经过的路由设备的域名及 IP地址,三个包每次来回所花时间. 转自 ...

  3. 清理oracle的用户中的日志垃圾以及修改sys用户的密码

    清理oracle的用户中的日志垃圾1.进入:/opt/oracle/product/11g/network/admin目录2.注释掉listener.ora文件中的TRACE_LEVEL_LISTEN ...

  4. 如何读懂statspack报告

    前言:这篇文章是我从网上找到的,但可惜不知道是哪位大侠写(译)的,因此这里无法注明了.仔细看了看,这篇文章对初学者应该很有帮助,写的比较详细,通俗易懂,因此整理一下,便于阅读:内容略有调整,不单做调整 ...

  5. java实现ftp文件上传下载,解决慢,中文乱码,多个文件下载等问题

    //文件上传 public static boolean uploadToFTP(String url,int port,String username,String password,String ...

  6. UNDO自我理解总结

    [场景] 当在更新数据的时候,发现更新的值写错了,这时就需要将已经更新的地方恢复到原始数据. [基本概念] 在更新的过程中,Oracle会将原始的数据都放入到UNDO里,这样当以上情况发生后,就可以从 ...

  7. Django 中form的用法

    form的主要作用:1.在html中生成表单框架,2.验证数据(实话实说,很简洁,但不实用,灵活性差) from django.db import models # Create your model ...

  8. XSS与CSRF两种跨站攻击总结

    在那个年代,大家一般用拼接字符串的方式来构造动态 SQL 语句创建应用,于是 SQL 注入成了很流行的攻击方式.在这个年代, 参数化查询 [1] 已经成了普遍用法,我们已经离 SQL 注入很远了.但是 ...

  9. Linux 用户篇——用户管理命令之useradd、passwd、userdel、usermod

    一.用户重要,用户管理命令同样重要 用户是Linux系统安全的核心,每个登录Linux系统的用户都会分配相应的权限,这些权限取决于能否访问系统中各种对象.而管理这些用户的相关信息离不开用户管理命令,比 ...

  10. GDB调试实用命令

    个人感觉从windows平台转到linux平台一个不适应的地方就是调试器的使用.因为windows下调试器基本上都依赖快捷键和图像界面来完成操作,就算是windbg这种伪命令行的工具,命令也很简单比较 ...