为了要重用Fragment的UI组件。你应该为它们每个都构建一个完整独立的,模块化的组件来定义他自身的布局和行为。

一旦你定义了这些可重用的Fragments。你能够通过activity关联它们同一时候通过应用逻辑连接它们来实现全部复杂的UI。

你通常都希望一个fragment可以和其它的fragment进行交互,比如基于用户的操作改变内容。全部的fragment之间的交流的完毕都通过activity的关联。两个fragment之间一定不要直接交流。

定义一个接口


要同意一个fragment和它的activity通讯。你可以在fragment类中定义一个接口。然后再activity中实现它。

Fragment在onAttach()方法中获取这个接口的实现,这样之后就行调用这些接口来达到和activity通讯的目的。

以下是一个fragment和activity通讯的样例:

public class HeadlinesFragment extends ListFragment {
    OnHeadlineSelectedListener mCallback;     // Container Activity must implement this interface
    public interface OnHeadlineSelectedListener {
        public void onArticleSelected(int position);
    }     @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
       
        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            mCallback = (OnHeadlineSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }
    }
   
    ...
}

如今这个fragment能够通过使用onHeadlineSelectedListener接口的实例mCallback来调用onArticleSelected() 方法(或者这个接口中的其他方法)来向activity传递消息了。

比如。当用户点击fragment中列表的item时,以下的方法将会被调用。这个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的接口。

比如,以下的这个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
    }
}

向Fragment传递消息


宿主activity能够通过使用findFragmentById()获取的fragment实例来向fragment传递消息。然后直接调用这些fragment的public方法。

比如,设想上面的那个activity包括还有一个fragment,这个fragment是用来展示通过前面的回调方法返回的数据指定的item。在这个案例中,这个activity能够这个activity能够将接收的这些信息传递给其他的fragment用来显示这个item:

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学习路径(23)应用Fragment建立动态UI——Fragment之间的通信的更多相关文章

  1. Android学习路径(22)应用Fragment建立动态UI——构建一个灵活UI

    当你设计你的应用来支持多个屏幕尺寸.你能够基于可用的屏幕空间通过在不同的布局上重用fragment来优化用户体验. 比如,在一个手机上.使用单面板(一次仅仅显示一个fragment)的用户体验更加合适 ...

  2. 9) 十分钟学会android--使用Fragment建立动态UI

    为了在 Android 上为用户提供动态的.多窗口的交互体验,需要将 UI 组件和 Activity 操作封装成模块进行使用,这样我们就可以在 Activity 中对这些模块进行切入切出操作.可以用  ...

  3. Android学习路径(七)建立Action Bar

    在action bar最今本的形式中,它只在左边展示了activity的标题以及应用的icon. 即使在这样的简单的形式中,它也不过告诉用户如今在应用的哪个activity中,同一时候为你的应用保持一 ...

  4. Android学习路线(二十四)ActionBar Fragment运用最佳实践

    转载请注明出处:http://blog.csdn.net/sweetvvck/article/details/38645297 通过前面的几篇博客.大家看到了Google是怎样解释action bar ...

  5. Android学习路线(二十一)运用Fragment构建动态UI——创建一个Fragment

    你能够把fragment看成是activity的模块化部分.它拥有自己的生命周期,接受它自己的输入事件,你能够在activity执行时加入或者删除它(有点像是一个"子activity&quo ...

  6. Android学习系列(23)--App主界面实现

    在上篇文章<Android学习系列(22)--App主界面比较>中我们浅略的分析了几个主界面布局,选了一个最大众化的经典布局.今天我们就这个经典布局,用代码具体的实现它. 1.预览图先看下 ...

  7. 我的android学习经历23

    学习fragment时遇到的问题 这几天学习fragment静态加载时遇到这样的问题: java.lang.RuntimeException: Unable to start activity Com ...

  8. 使用Fragment 实现动态UI 和 动态添加Fragment

    首先写好每个Fragment: 1.在第一个Fragment写一个按钮,使其加载下一个Fragment 布局: <LinearLayout xmlns:android="http:// ...

  9. Android学习笔记(九)一个例子弄清Service与Activity通信

    上一篇博文主要整理了Service的创建.绑定过程,本篇主要整理一下Service与Activity的通信方式.包括在启动一个Service时向它传递数据.怎样改变运行中的Service中得数据和侦听 ...

随机推荐

  1. Test oracle db iops

    Today, i need to test one database's iops and do something for oracle db's io test. How to test the ...

  2. [黑马程序员] 集合框架2——Map系 & 集合工具类(Collections、Arrays)

    ---------------------- ASP.Net+Android+IO开发..Net培训.期待与您交流! ---------------------- 0. 集合框架按其所实现的接口, 大 ...

  3. Windows XP环境下 搭建Android NDK环境

    搭建Android NDK环境 Windows XP环境下 1 一些下载 ① NDK r7:http://developer.android.com/sdk/ndk/index.html ② cygw ...

  4. linux ifconfig命令使用详解

    Linux下网卡命名规律:eth0,eth1.第一块以太网卡,第二块.lo为环回接口,它的IP地址固定为127.0.0.1,掩码8位.它代表你的机器本身. 1.ifconfig是查看网卡的信息. if ...

  5. 程序缩小到托盘后系统就无法关机(解决方案)——处理WM_QUERYENDSESSION消息,并把它标识为处理过了

    程序缩小到托盘后系统就无法关机(解决方案)                       老帅    程序最小化到托盘后,会出现系统无法关闭的问题,常见于WinXP系统中,这里提供一个解决方案!一.解决 ...

  6. 终于懂了:TControl.Perform是有返回值的,且看VCL框架如何利用消息的返回值(全部例子都在这里)——它的存在仅仅是为了方便复用消息的返回值

    代码如下: function TControl.Perform(Msg: Cardinal; WParam, LParam: Longint): Longint; var Message: TMess ...

  7. hdu 4970 Killing Monsters(数学题)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4970 Problem Description Kingdom Rush is a popular TD ...

  8. BZOJ 1367([Baltic2004]sequence-左偏树+中位数贪心)

    1367: [Baltic2004]sequence Time Limit: 20 Sec   Memory Limit: 64 MB Submit: 521   Solved: 159 [ Subm ...

  9. ExtJS4.2学习(7)——基础知识之Reader&Writer篇

    Reader: 主要用于将proxy数据代理读取的数据按照不同的规则进行解析,将解析好的数据保存到Modle中. 结构图 Ext.data.reader.Reader 读取器的根类(很少直接实例化这个 ...

  10. android--手机桌面添加网址链接图标(解决方式)

    这样的做法最普遍最简单: 1.新建一个android空项目: 2.在drawable文件夹下加入图标文件,如icon.png:在values文件夹下的strings.xml文件里添加名称.如websi ...