[转][译][Android基础]Android Fragment之间的通信
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之间的通信的更多相关文章
- Android使用Fragment来实现ViewPager的功能(解决切换Fragment状态不保存)以及各个Fragment之间的通信
以下内容为原创,转载请注明:http://www.cnblogs.com/tiantianbyconan/p/3364728.html 我前两天写过一篇博客<Android使用Fragment来 ...
- Android使用Fragment来实现TabHost的功能(解决切换Fragment状态不保存)以及各个Fragment之间的通信
以下内容为原创,转载请注明:http://www.cnblogs.com/tiantianbyconan/p/3360938.html 如新浪微博下面的标签切换功能,我以前也写过一篇博文(http:/ ...
- Fragment的生命周期&同一Activity下不同Fragment之间的通信
Android开发:碎片Fragment完全解析(2) Fragment的生命周期 和Activity一样,Fragment也有自己的生命周期,理解Fragment的生命周期非常重要,我们通过代码的方 ...
- Fragment之间的通信(四)
自定义两个fragment的布局和java类. 在mainactivity中引用布局文件 在其中的一个fragment中的控件上添加监听,获取到另一个fragment中控件的内容,展示出来完成frag ...
- Android中使用开源框架EventBus3.0实现Fragment之间的通信交互
1.概述 在之前的博文中简单介绍过如何实现fragment之间的信息交互:<Android中Fragment与Activity之间的交互(两种实现方式)>,今天继续给大家介绍一种可以实现此 ...
- Android - Fragment (三)不同Fragment之间的通信
在Fragment的java文件中,可以使用getActivity()来获得调用它的activity, 然后再找到另一个Fragment,进行通信 getActivity().getFragmentM ...
- <Android基础>(四) Fragment Part 1
Fragment 1)Fragment的简单用法 2)动态添加Fragment 3)在Fragment中模拟返回栈 4)Fragment和活动之间通信 第四章 Fragment Fragment是一种 ...
- Android Fragment之间的通信(用fragment替换掉XML布局文件中的一个线性布局)
1.XML布局 (1)主界面 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xml ...
- <Android基础> (四) Fragment Part 2
4.3 Fragment的生命周期 4.3.1 Fragment的状态和回调 1.运行状态 当一个Fragment是可见的,并且它关联的活动正处于运行状态是,该Fragment也处于运行状态 2.暂停 ...
随机推荐
- python简单爬虫(二)
上一篇简单的实现了获取url返回的内容,在这一篇就要第返回的内容进行提取,并将结果保存到html中. 一 . 需求: 抓取主页面:百度百科Python词条 https://baike.baidu. ...
- juery中监听input的变化事件
$('#searchValue').bind('input propertychange', function() { searchFundList(); });
- 多个id或class属性相同的元素绑定事件
<td class="tools"><a href="javascript:void(0);" status="0" na ...
- sql server 2008 r2 产品密钥
数据中心版:PTTFM-X467G-P7RH2-3Q6CG-4DMYBDDT3B-8W62X-P9JD6-8MX7M-HWK38==================================== ...
- 全局应用程序类(Global.asax)
注:该部分参考的园区的“积少成多”的 <ASP.NET MVC中的Global.asax文件> . 1.Global.asax文件介绍 global.asax这个文件包含全局应用程序事件 ...
- [How to] 使用HBase协处理器---基本概念和regionObserver的简单实现
1. 简介 对于HBase的协处理器概念可由其官方博文了解:https://blogs.apache.org/hbase/entry/coprocessor_introduction 总体来说其包含两 ...
- yum和head一起用,报错“由于管道被破坏而退出”
当要打印 [yum list ]时, 加上了管道符 以及 head 会出现报错 “由于管道被破坏而退出” 是因为 yum 与 head 连用 存在bug ,如果使用tail 则没有出现 具体什么bug ...
- chm转换为html文件
在Windows下chm转换为html的超简单方法(反编译CHM文件的方法) 通过调用Windows命令,将chm 文件转换为html 文件. 方法: 命令行(cmd),输入hh -decompile ...
- LeetCode765. Couples Holding Hands
N couples sit in 2N seats arranged in a row and want to hold hands. We want to know the minimum numb ...
- python datetime 时区(timezone) dateutil
记录下python中的时区问题, 代码如下: 包括datetime.datetime对象使用不同的时区,以及在不同时区间转换. from datetime import datetime from ...