【问题标题】:Can a fragment implement two interfaces from its parent activity?片段可以从其父活动中实现两个接口吗?
【发布时间】:2014-07-21 03:38:52
【问题描述】:

为了在 Fragment 之间进行通信,我们使用父 Activity 实现的接口模式...就像在文档中一样,例如 Fragment 可以在其附加到 Activity 时获取父接口。

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");
        }
    }

...
}

但是比如说父 Activity 实现了另一个接口

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

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

【问题讨论】:

    标签: android android-fragments interface


    【解决方案1】:

    当然,只需施放两次:

    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");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-25
      相关资源
      最近更新 更多