1

As far as I know it is recommended to attach InteractionListener interface to a fragment inside the onAttach method like this

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

Thus we are sure that it will be properly reattached in case of recreating (changing screen orientation, memory reallocation, etc...).

But it's for Activity as a parent. What if I have nested fragments and I want the parent fragment to implement InteractionListener? Who do I do then?

T.Vert
  • 279
  • 2
  • 13

1 Answers1

1

You can use getParentFragment() method of 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");
        }
    }
}

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

vovahost
  • 34,185
  • 17
  • 113
  • 116