Kaidul
Kaidul

Reputation: 15915

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()?

Upvotes: 10

Views: 2282

Answers (1)

Marcin Orlowski
Marcin Orlowski

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

Related Questions