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

时间:2015-10-21 09:43:15

标签: android android-fragments android-fragmentactivity android-lifecycle

由于在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");

    }

2 个答案:

答案 0 :(得分:14)

代码将保持不变,只需按照documentation使用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");

    }

答案 1 :(得分:3)

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

onAttach(Context context)

并检查它是否包含某个界面:

public void onAttach(Context context) {

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