本文介绍了onAttach(活动)去precated:我在哪里可以检查活动实现回调接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

23 API之前,我用碎片的onAttach方法来让我的听众实例,则引用内部onDetach清洗。例如:

Before API 23 I used Fragment's onAttach methods to get my listener instance, then the reference is cleaned inside onDetach. ex:

@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(上下文的背景下)内相同的检查,或是否有更好的方式来获得持有人的活动实例?

Is it safe to do the same check inside onAttach(Context context) or is there a better way to get the holder activity instance?

推荐答案

检查源$ C ​​$ C:

Check the source code:

/**
 * 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(活动活动)被称为由 onAttach(上下文的背景下),如果有一台主机活动。您可以使用 onAttach(活动活动)安全。

So the onAttach(Activity activity) is called by the onAttach(Context context) if there is a host activity. You can use the onAttach(Activity activity) safely.

这篇关于onAttach(活动)去precated:我在哪里可以检查活动实现回调接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 17:08