I'm writing an app that has a parent Activity
and several child Fragments
. I am trying to get the Fragment to communicate back to the parent Activity. I know there are several ways to do this, including making an interface and implementing that in the parent Activity. However, I am interested in this method:
ParentActivity activity = (ParentActivity) getActivity();
activity.someMethod();
This approach takes less code and is less complex. However, is this cast safe to do in production code? Or is an interface safer?
You can use this -
private ParentActivity callback;
@Override
public void onAttach(Activity activity)
{
//callback = (ParentActivity ) activity;
// make sure there is no cast exception
callback = (ParentActivty.class.isAssignableFrom(activity
.getClass())) ? (ParentActivity) activity : null;
super.onAttach(activity);
}
@Override
public void onDetach()
{
callback = null;
super.onDetach();
}
now when you do any method call , call it like this -
if(callback!=null)
{
callback.someMethod();
}
this method is safe .
It is safe (i.e. you won't get a ClassCastException
), as long as you make sure that only ParentActivity
ever creates/adds your Fragment.
These classes are now effectively coupled, which is, in general, not a good thing.
By casting to a specific Activity class (ParentActivity), you are losing the ability to re-use the fragment with different activities. It's safe to cast, as long as you only use the fragment with that one activity.
Using an interface allows the fragment to be used with multiple activities - you just need to implement the interface in the activities that use the fragment.
Another option is to use an Event Bus - like GreenRobot's EventBus or Square's Otto
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