为了可以复用一个fragment,所以在定义fragment的时候,要把它定义为一个完全独立和模块化,它有它自己的layout和行为。当你定义好了这些可复用的fragment,可以把他们和activity相关联,在应用的逻辑基础上把这些fragment相互关联,从而组成一个完整的UI。

很多时候,我们需要fragment直接进行通信,比方说,根据用户的动作交换内容。所有的fragment直接的通信,都是利用与之关联的activity.2个fragment永远不可能直接通信。

定义接口

要允许fragment和它所在的activity通信,你可以在Fragment类里面定义一个接口,然后在activity里面实现这个接口。Fragment会在它的生命周期函数:onAttach()期间捕获这个接口的实现。然后就可以调用这个接口的方法和activity通信了。

下面是一个通信的例子:

 1 public class HeadlinesFragment extends ListFragment {
 2     OnHeadlineSelectedListener mCallback;
 3 
 4     // Container Activity must implement this interface
 5     public interface OnHeadlineSelectedListener {
 6         public void onArticleSelected(int position);
 7     }
 8 
 9     @Override
10     public void onAttach(Activity activity) {
11         super.onAttach(activity);
12         
13         // This makes sure that the container activity has implemented
14         // the callback interface. If not, it throws an exception
15         try {
16             mCallback = (OnHeadlineSelectedListener) activity;
17         } catch (ClassCastException e) {
18             throw new ClassCastException(activity.toString()
19                     + " must implement OnHeadlineSelectedListener");
20         }
21     }
22     
23     ...
24 }
View Code

相关文章:

  • 2021-08-05
  • 2022-12-23
  • 2021-12-08
  • 2022-12-23
  • 2022-12-23
  • 2021-06-03
猜你喜欢
  • 2021-07-04
  • 2021-12-06
  • 2021-09-21
  • 2021-06-04
  • 2022-02-24
相关资源
相似解决方案