注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好。
    
      
        原文链接:
        
          http://developer.android.com/training/basics/fragments/communicating.html
        
      
      
        
      
    
  
为了重用Fragment UI组件,你应该将每一个组件构建为自控地,模块化的组件,它们有自己的布局和行为。一旦你定义好了这些可重用的fragment,你就可以将他们与activity关联,通过应用逻辑将它们连接起来,以此实现一个整体复合的界面。
你经常会希望一个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可以通过调用 onArticleSelected()方法(或其他接口中的方法)向 activity发送消息了。在此例中,使用的是 OnHeadlineSelectedListener接口的实例: mCallback。
比如:下面所示的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的事件回调,宿主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。
举一个例子:我们想象上述的Activity可能还容纳了另一个fragment,它用来展示上述回调方法中岁返回特定项的数据。在这个例子中,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();
        }
    }
}
      
    
  

