利用Fragment创建动态UI 之 Fragment之间的通信
2013-07-03 11:55
399 查看
为了可以复用一个fragment,所以在定义fragment的时候,要把它定义为一个完全独立和模块化,它有它自己的layout和行为。当你定义好了这些可复用的fragment,可以把他们和activity相关联,在应用的逻辑基础上把这些fragment相互关联,从而组成一个完整的UI。
很多时候,我们需要fragment直接进行通信,比方说,根据用户的动作交换内容。所有的fragment直接的通信,都是利用与之关联的activity.2个fragment永远不可能直接通信。
定义接口
要允许fragment和它所在的activity通信,你可以在Fragment类里面定义一个接口,然后在activity里面实现这个接口。Fragment会在它的生命周期函数:onAttach()期间捕获这个接口的实现。然后就可以调用这个接口的方法和activity通信了。
下面是一个通信的例子:
View Code
很多时候,我们需要fragment直接进行通信,比方说,根据用户的动作交换内容。所有的fragment直接的通信,都是利用与之关联的activity.2个fragment永远不可能直接通信。
定义接口
要允许fragment和它所在的activity通信,你可以在Fragment类里面定义一个接口,然后在activity里面实现这个接口。Fragment会在它的生命周期函数:onAttach()期间捕获这个接口的实现。然后就可以调用这个接口的方法和activity通信了。
下面是一个通信的例子:
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(); } } }
View Code
相关文章推荐
- 利用Fragment创建动态UI 之 Fragment之间的通信
- Training--使用Fragment创建动态UI(3)-- 与其他Fragment通信
- 【Android Training - 03】使用Fragments建立动态的UI [ Lesson 4 - Fragment之间的通信 ]
- Android学习路径(23)应用Fragment建立动态UI——Fragment之间的通信
- 利用Fragment创建动态UI 之 创建一个Fragment
- Android -- fragment, 动态创建,创建选项卡,静态创建,fragment之间的通信
- 利用Fragment创建动态UI 之 使用Support Library
- 利用Fragment创建动态UI 之 创建一个灵活的UI
- 【Android Training - 03】使用Fragments建立动态的UI [ Lesson 4 - Fragment之间的通信 ]
- [Andriod官方训练教程]使用Fragment创建一个动态的UI之使用Support Library
- [Andriod官方训练教程]使用Fragment创建一个动态的UI之与其他Fragments进行交互
- [Andriod官方训练教程]使用Fragment创建一个动态的UI之使用Support Library
- Training--使用Fragment创建动态UI(2)--构建一个灵活的UI
- Android开发之利用Fragment建立动态UI
- 使用Fragment创建动态UI
- 利用Fragment之间的通信切换标签页
- Android Training - 使用碎片创建一个动态UI(4) - 与其他碎片通信
- fragment与activity之间的利用接口通信
- [Andriod官方训练教程]使用Fragment创建一个动态的UI之创建一个Fragment
- Android官方开发文档Training系列课程中文版:使用Fragment构建动态UI之Fragment创建