使用内部片段设置 InteractionListener

Setting InteractionListener with inner fragment

据我所知,建议像这样将 InteractionListener 接口附加到 onAttach 方法内的片段

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

因此我们确信在重新创建(更改屏幕方向、内存重新分配等...)时它会被正确地重新附加。

但它是 Activity 作为 parent 的。如果我有嵌套片段并且我希望 parent 片段实现 InteractionListener 怎么办?那我找谁呢?

您可以使用 getParentFragment() 方法 Fragment class:

@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()