如何在onAttach(活动活动)被解除后检查活动是否实现了接口

Jos*_*hon 5 android android-lifecycle android-fragments android-fragmentactivity

由于onTttach(Activity)已在SDK 23上弃用,这是Fragment生命周期中用于检查Activity是否正在实现接口的最佳方法?

此代码不再正确,将来甚至可以删除此方法.

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

        if (activity instanceof OnInterfaceOfFragmentListener)
            mCallback = (OnInterfaceOfFragmentListener) activity;
        else
            throw new RuntimeException("OnInterfaceOfFragmentListener not implemented in activity");

    }
Run Code Online (Sandbox Code Playgroud)

fra*_*nch 14

根据文档,代码将保持不变,只是您应该使用Context参数而不是Activity .

@Override
    public void onAttach(Context context) {
        super.onAttach(context);

        if (context instanceof OnInterfaceOfFragmentListener)
            mCallback = (OnInterfaceOfFragmentListener) context;
        else
            throw new RuntimeException("OnInterfaceOfFragmentListener not implemented in context");

    }
Run Code Online (Sandbox Code Playgroud)