2016-09-27 64 views
1

據我所知建議InteractionListener接口連接到一個片段onAttach方法這樣設置InteractionListener與內片段

@Override 
public void onAttach(Activity activity) { 
    super.onAttach(activity); 
    if (activity instanceof OnFragmentInteractionListener) { 
     mListener = (OnFragmentInteractionListener) activity; 
    } else { 
     throw new RuntimeException(activity.toString() 
       + " must implement OnFragmentInteractionListener"); 
    } 
} 

內因此,我們相信,它會在重建的情況下,可以適當地重新連接(改變屏幕方向,內存重新分配等)。

但它是作爲家長的活動。如果我有嵌套的片段,並且我希望父片段實現InteractionListener,該怎麼辦?那麼我該怎麼做?

回答

1

可以使用Fragment類的getParentFragment()方法:

@Override 
public void onAttach(Activity activity) { 
    super.onAttach(activity); 
    Fragment parentFragment = getParentFragment(); 
    if (parentFragment != null) { 
     if (parentFragment instanceof OnFragmentInteractionListener) { 
      mListener = (OnFragmentInteractionListener) parentFragment; 
     } else { 
      throw new RuntimeException(parentFragment.toString() 
        + " must implement OnFragmentInteractionListener"); 
     } 
    } 
} 

來源:https://developer.android.com/reference/android/app/Fragment.html#getParentFragment()