Android Fragment---跟Activity通信


Android Fragment---跟Activity通信

 方法一:

 

尽管Fragment是作为一个独立于Activity来实现的一个对象,并且能够在多个Activity内部使用,但是一个给定的Fragment实例直接被捆绑包含它的Activity中。

特别是Fragment能够使用getActivity()方法访问Activity的实例,并且很容易执行如在Activity布局中查找视图的任务:

View listView = getActivity().findViewById(R.id.list);

同样Activity通过从FragmentManager中获得的Fragment引用也能够调用Fragment中的方法,使用findFragmentById()或findFragmentByTag()方法获取Fragment引用,例如:

ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);

 

 

方法二:

 

为了重用Fragment的UI组件,创建的每个Fragment都应该是自包含的、有它自己的布局和行为的模块化组件。一旦你定义了这些可重用的Fragment,你就可以把它们跟一个Activity关联,并把它们跟应用程序的逻辑相连来实现全部的组合式UI。

      现实中我们经常想要一个Fragment跟另一个Fragment进行通信,例如,要基于一个用户事件来改变内容。所有的Fragment间的通信都是通过跟关联的Activity来完成的。另个Fragment不应该直接通信。也就是说Fragment间不直接通信,通过Activity转一下,按java常规,转一下多是使用Interface实现的。

定义Interface

      为了让Fragment跟它的Activity通信,你可以在Fragment类中定义一个接口,并在它所属的Activity中实现该接口。Fragment在它的onAttach()方法执行期间捕获该接口的实现,然后就可以调用接口方法,以便跟Activity通信。

以下是Fragment跟Activity通信的示例:

双击代码全选
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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就可以通过调用OnHealdlineSelectedListener接口实例mCallback的onArticleSelected()方法(或其他的接口中的方法)给Activity发送消息。

例如,在Fragment中的下列方法会用户点击列表项时被调用。该Fragment使用回调接口把该事件发送给它的父Activity。

双击代码全选
1
2
3
4
5
@Override
    public void onListItemClick(ListView l, View v, int position, long id) {    
        // Send the event to the host activity    
        mCallback.onArticleSelected(position);    
    }

实现Interface

为了从Fragment中接收事件回调,包含Fragment的Activity必须实现Fragment类中定义的接口。

例如,下面Activity实现了上面示例中定义的接口:

双击代码全选
1
2
3
4
5
6
7
8
9
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

        通过使用findFragmentById()方法捕获Fragment实例,宿主Activity可以把消息发送给该Fragment,然后直接调用该Fragment的公共方法。

       例如,上面的示例,Activty通过Interface的实现方法,传递数据到另一个Fragment。

双击代码全选
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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();    
         }    
     }    
}

Fragment中使用左右滑动菜单 中应用到了Fragment间的通信

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值