草庐IT

android - onAttach(Activity) 已弃用 : where I can check if the activity implements callback interface

coder 2023-06-08 原文

在 API 23 之前,我使用 Fragment 的 onAttach 方法来获取我的监听器实例,然后在 onDetach 中清除引用。例如:

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    mListener = null;
    try {
        mListener = (SellFragmentListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement SellFragmentListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

在 onAttach(Context context) 内部做同样的检查是否安全,或者有没有更好的方法来获取持有者 Activity 实例?

最佳答案

查看源代码:

/**
 * Called when a fragment is first attached to its context.
 * {@link #onCreate(Bundle)} will be called after this.
 */
public void onAttach(Context context) {
    mCalled = true;
    final Activity hostActivity = mHost == null ? null : mHost.getActivity();
    if (hostActivity != null) {
        mCalled = false;
        onAttach(hostActivity);
    }
}

/**
 * @deprecated Use {@link #onAttach(Context)} instead.
 */
@Deprecated
public void onAttach(Activity activity) {
    mCalled = true;
}

所以 onAttach(Activity activity) 如果存在宿主 Activity ,则由 onAttach(Context context) 调用。您可以安全地使用 onAttach(Activity activity)

关于android - onAttach(Activity) 已弃用 : where I can check if the activity implements callback interface,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32258125/

有关android - onAttach(Activity) 已弃用 : where I can check if the activity implements callback interface的更多相关文章

随机推荐