Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fragment interaction callbacks: onAttach() vs setter

I'm trying to implement a nice, reusable Fragment and I'm having a hard time choosing a pattern of setting interaction callbacks. I am of course familiar with the docs, but I have some doubts regarding the method described therein.

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

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

So far I've encountered two methods of setting callbacks for Fragments.

1. Casting Context in onAttach()

The way described in the 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 much code to write
  • mCallbacks will never be null (as long as the Fragment is alive)

Cons:

  • Will get messy if we use multiple Fragments in the Activity
  • Conflicts when trying to use multiple instances of the same Fragment class
  • Weird flow when using nested Fragments

2. A setter

Simple listener pattern.

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

Pros

  • Can set and replace callbacks from anywhere
  • Can use anonymous (or inner static) callback classes

Cons

  • Needs nullchecks before calling callback methods
  • Does not automatically bind on Fragment recreation (easily fixed by setting callbacks in the Activity's onAttachFragment)

I find the first method to be inferior to the second, because it introduces unnecessary limitations and violates LoD to some degree by requiring callback methods to be implemented by the Activity to which the Fragment is attached. It also makes interaction with nest fragments complicated by forcing that the callbacks are sent all the way up to the Activity instead of just to the parent Fragment. Then again, this is the method suggested in the Android dev guide. Am I missing something here?

Long question short, what is the best practice for implementing Fragment callbacks?

like image 818
SpaceBison Avatar asked Jun 16 '17 10:06

SpaceBison


1 Answers

I usually use the officially documented method. On the rare occasions when it doesn't quite fit with my app structure\complexity, I find that the EventBus model usually works nicely instead.

https://github.com/greenrobot/EventBus

like image 80
Kuffs Avatar answered Oct 25 '22 02:10

Kuffs