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()
?
The communication between fragments should not be done directly. There are two ways of doing so. To have a sharing of data between Fragments, either you can use a shared ViewModel that is shared between all the Fragments or you can make an Interface and then use this interface to communicate between fragments.
We can communicate within fragments using the ViewModel. We can also communicate between fragments using Interface.
Two Fragments should never communicate directly. The reason for this is that Fragment s are fluid & dynamic UI components that may fade in and out of view. Only the hosting Activity is capable of determining if a Fragment is added to the UI or has been detached from it.
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.
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