作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
在 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/
我是一名优秀的程序员,十分优秀!