Reputation: 15915
I can easily communicate between two fragment
s of an activity by callback interface
. Following that way, I have implemented an interface in ParentFragment
to communicate.
But in case of activity, I was using -
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallback = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
And in current case, I am using mCallback = (OnHeadlineSelectedListener) getParentFragment();
instead of mCallback = (OnHeadlineSelectedListener) activity;
. Everything is working well. Is this approach okay? Or should I do it into another thread instead onAttach()
?
Upvotes: 10
Views: 2282
Reputation: 75635
The cast thing is to ensure certain object is instance of class that implements given interface (in this case OnHeadlineSelectedListener
). It's irrelevant at this point what type of object it is be it activity, fragment or anything else. As long as it implements the interface you need, it is all fine.
Upvotes: 7