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.
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");
}
}
mCallbacks
will never be null (as long as the Fragment is alive)Simple listener pattern.
public void setCallbacks(Callbacks callbacks) {
mCallbacks = callbacks;
}
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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With