片段可以从其父活动实现两个接口吗?

时间:2014-07-21 03:38:53

标签: android android-fragments interface

为了在片段之间进行通信,我们使用父活动实现的接口模式...就像在文档中一样,例如片段可以在其对活动的附件上获得父接口。

public class HeadlinesFragment extends ListFragment {
    OnHeadlineSelectedListener mCallback;

    // Container Activity must implement this interface
    public interface OnHeadlineSelectedListener {
        public void onArticleSelected(int position);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            mCallback = (OnHeadlineSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }
    }

...
}

但是比如说,父活动实现了另一个接口

public interface OnThreadCliked{
    void onThreadClicked(Post post);
}

有没有办法获得对活动实现的第二个接口的引用?

1 个答案:

答案 0 :(得分:5)

当然,只需投两次:

OnThreadCliked mCallback2;

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    // This makes sure that the container activity has implemented
    // the callback interface. If not, it throws an exception
    try {
        mCallback = (OnHeadlineSelectedListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnHeadlineSelectedListener");
    }

    // This makes sure that the container activity has implemented
    // the second callback interface. If not, it throws an exception
    try {
        mCallback2 = (OnThreadCliked) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnThreadCliked");
    }
}
相关问题