2014-07-21 62 views
2

爲了在片段之間進行通信,我們使用父活動實現的接口模式......就像在文檔中一樣,片段可以在其活動附件上獲得父接口。一個片段可以從其父活動實現兩個接口嗎?

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"); 
     } 
    } 

... 
} 

但是比方說父活動實現另一個接口

public interface OnThreadCliked{ 
    void onThreadClicked(Post post); 
} 

有沒有辦法讓參照第二界面活性工具?

回答

4

當然,只投了兩次:

OnThreadCliked mCallback2; 

@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"); 
    } 

    // This makes sure that the container activity has implemented 
    // the second callback interface. If not, it throws an exception 
    try { 
     mCallback2 = (OnThreadCliked) activity; 
    } catch (ClassCastException e) { 
     throw new ClassCastException(activity.toString() 
       + " must implement OnThreadCliked"); 
    } 
} 
相關問題