bcorso bcorso - 10 months ago 132
Android Question

Android nested fragment-fragment interactions

Android best practices for fragment-fragment interaction (described here and here) forces the

to implement a listener defined by the child fragment. The
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

    public void onAttach(Activity activity) {

    try {
    mCallback = (OnHeadlineSelectedListener) activity;
    } catch (ClassCastException e) {
    throw new ClassCastException(activity.toString()
    + " must implement OnHeadlineSelectedListener");

Answer Source

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.