gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 23:10:03 24 4
gpt4 key购买 nike

在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com