如何在 onAttach(Activity activity) 被弃用后检查 activity 是否实现了接口

how check if an activity implements an interface after onAttach(Activity activity) has been depreacted

由于 SDK 23 已弃用 onAttach(Activity),这是 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");

    }

您可以使用框架提供的替代方法。它在生命周期中的位置与 onAttach(Activity)

相同

onAttach(Context context)

并检查它是否实现了某个接口:

public void onAttach(Context context) {

  if(context instanceOf YourInterface) {
       // do stuff
  }
  else
     throw new RuntimeException("XYZ interface not implemnted");
}

代码将保持不变,只是您应该根据 documentation.

使用上下文参数而不是 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");

    }