10

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

4

1 回答 1

7

强制转换是确保某个对象是实现给定接口的类的实例(在这种情况下OnHeadlineSelectedListener)。在这一点上,它是什么类型的对象是无关紧要的,它是活动、片段还是其他任何东西。只要实现了你需要的接口,一切都好。

于 2013-08-12T22:22:45.620 回答