Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to communicate between two child Fragments inside a Nested Fragment

I can easily communicate between two fragments 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()?

like image 832
Kaidul Avatar asked Aug 12 '13 22:08

Kaidul


People also ask

Could two fragments can communicate directly?

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.

How does a fragment communicate with other fragments?

We can communicate within fragments using the ViewModel. We can also communicate between fragments using Interface.

Why two fragments should never communicate directly?

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.


1 Answers

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.

like image 122
Marcin Orlowski Avatar answered Sep 21 '22 17:09

Marcin Orlowski