Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android nested fragment-fragment interactions

Android best practices for fragment-fragment interaction (described here and here) forces the Activity to implement a listener defined by the child fragment. The Activity then manages the communication between fragments.

From my understanding this is to keep the fragments loosely coupled from each other. However,

  1. Is this also the case for nested fragments? I can imagine it might make sense for a nested fragment to report directly to it's parent fragment instead of the Activity.

  2. If a nested fragment has its parent fragment implement it's listener, how would one (or should one) require the parent fragment to do this. In other words, is a similar to the paradigm to the following but for Fragments:

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    
        try {
            mCallback = (OnHeadlineSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }
    }
    
like image 786
bcorso Avatar asked Aug 28 '14 22:08

bcorso


2 Answers

If anyone wanted an example of an implementation that ensures parent context implements the callbacks while not caring whether it is an activity or fragment, the following worked for me:

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof Callbacks) {
        mCallbacks = (Callbacks) context;
    } else {
        if (getParentFragment() != null && getParentFragment() instanceof Callbacks) {
            mCallbacks = (Callbacks) getParentFragment();
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement " + TAG + ".Callbacks");
        }
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mCallbacks = null;
}

Enjoy!

like image 114
Michael Garner Avatar answered Oct 18 '22 20:10

Michael Garner


As long as you define an interface in the fragment, you can have the parent activity or parent fragment implementing it. There is no rule that says fragment should not implement interface of a child fragment. One example where this make sense is that fragment A has two children Fragments B, C. A implements B's interface, when A gets a call back, it might need to update fragment C. Exactly the same thing with activity, just different level.

like image 31
CChi Avatar answered Oct 18 '22 21:10

CChi