Fragment interaction callbacks: onAttach () vs setter

I am trying to implement a nice, reusable snippet and am having a hard time choosing a custom interaction callback setup pattern. I am of course familiar with the docs , but I have some doubts about the method described in it.

Let's say we have a snippet with a callback interface:

public class MyFragment extends Fragment {
    private Callbacks mCallbacks;
    public static interface Callbacks { /* ... */ }
}

      

So far, I've come across two methods for setting callbacks for fragments.

1. The context of casting in onAttach()

Method described in Android dev guide.

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    try {
        mCallbacks = (Callbacks) context;
    } catch (ClassCastException e) {
        throw new ClassCastException(context.toString() + " must implement Callbacks");
    }
}

      

Pros:

  • Not a lot of code to write
  • mCallbacks

    will never be null (as long as the fragment is alive)

Minuses:

  • It will be messy if we use multiple fragments in an Activity
  • Conflicts when trying to use multiple instances of the same Fragment class
  • Strange flow when using nested fragments

2. Organizer

A simple listener template.

public void setCallbacks(Callbacks callbacks) {
    mCallbacks = callbacks;
}

      

Pros

  • Can set and replace callbacks from anywhere
  • Anonymous (or internal static) callback classes can be used

Against

  • Requires nullchecks before calling callback methods
  • Doesn't bind automatically to rest of fragments (easily installable by setting callbacks in onAttachFragment

    )

I believe the first method is inferior to the second as it introduces unnecessary constraints and violates LoD to some extent by requiring callback methods to be implemented by the Activity to which the fragment is attached. It also makes interacting with socket fragments tricky by forcing callbacks to be dispatched all the way down to the Activity and not just to the parent fragment. Again, this is the method suggested in the Android dev guide. Did I miss something?

In short, what's the best practice for doing fragment callbacks?

+3


source to share


1 answer


I usually use the officially documented method. In the rare cases where it doesn't quite fit my application structure \ complexity, I find the EventBus model usually works nicely.



https://github.com/greenrobot/EventBus

0


source







All Articles