我们如何保证 onAttach 始终有效(Fragment)?

How can we guarantee onAttach will always work (Fragment)?

有什么方法可以保证 onAttach 有效吗?

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
}

如果我稍后在片段中调用 getActivity(),我应该担心并始终这样做:

if(getActivity()!=null)

如果是null怎么办?

片段流的顺序是:

If I call getActivity() later down in the fragment, should I be concerned and always do: if(getActivity()!=null)

这取决于 "later down in the fragment" 的性质。在主应用程序线程上,在调用 onAttach()onDetach() 之间,getActivity() 应该 return 一个非 null 值。然而:

  • 如果您的片段正在管理 AsyncTask 或其他后台线程,则在 attaching/detaching 发生时(例如,配置更改)可能会继续对该线程的调用,并且因此,此类后台线程不应尝试引用 activity

  • 如果您不确定在 onAttach()onDetach() 之间调用的方法,练习防御性编程并验证您得到的 ActivitygetActivity() 回来不是 null

And what should I do if it is null?

优雅地失败。除此之外,我们无法为您提供建议,因为我们不知道您要用 activity.

做什么