从 `onCreateView` 调用 `getActivity()` 是否安全?

Is it safe to call `getActivity()` from `onCreateView`?

查看 Fragment 生命周期(例如 ),Activity 似乎在发出任何其他回调之前附加到 Fragment(这是由 onAttach() 方法通知的).

在我的应用程序中,它由一个 activity 组成,第一个片段是从 Activity 的 onCreate() 方法打开的(实际上这是在 onCreate()).

目前,我正在 onCreateView() 回调中初始化我的所有图形元素,包括需要构造 Activity 的某些对象(如 ArrayAdapter)的实例化,这是通过调用 getActivity() 获得的。我假设 Activity 此时保证存在,因为 onAttach() 方法已经被调用。
我注意到 IntelliJ 警告我 getActivity() 返回 null 的可能性,可能只是因为该方法被注释为 @Nullable,所以我开始在网上搜索我的假设是否真的正确,现在我很困惑:在 onCreateView() 中调用 getActivity() 真的安全吗?为什么有一个名为 onActivityCreated() 的方法(我知道它现在已被弃用,但它确实起到了一定的作用)?

遗憾的是,文档无法帮助理解这一点。

根据 official Fragment lifecycle documentation:

FragmentManager is also responsible for attaching fragments to their host activity and detaching them when the fragment is no longer in use. The Fragment class has two callback methods, onAttach() and onDetach(), that you can override to perform work when either of these events occur.

所以在 onAttach()onDetach() 之间,getActivity() 总是 return 一个非 null Activity 并且该页面继续说:

onAttach() is always called before any Lifecycle state changes.

onDetach() is always called after any Lifecycle state changes.

所以,是的,onCreateView() 作为生命周期状态更改,将意味着 getActivity() return 是一个非空值。

这正是 requireActivity() 的用例 - 它允许您告诉片段系统您 在那个时间点知道 getActivity() return 将是一个非空值,并且您希望编译时保证 requireActivity() 调用之后的任何代码都可以访问非空值 Activity.

至于 onActivityCreated(),根据 :

,这是一个非常糟糕的命名方法

You have never needed to wait for onActivityCreated() to call requireActivity() or getActivity() - those are both available as soon as the Fragment is attached to the FragmentManager and hence can be used in onAttach(), onCreate(), onCreateView(), onViewCreated() all before onActivityCreated() is called.

This is one of the reasons why onActivityCreated() was deprecated - it actually has nothing to do with the activity becoming available to the Fragment, nor does it have anything to do with the activity finishing its onCreate() (it, in fact, can be called multiple times - every time the Fragment's view is created, not just once after the first time the Activity finishes onCreate()).

当然,请注意像 ArrayAdapter 这样的 API 而不是 需要 Activity - 它们需要 ContextgetContext()requireContext() 中有类似的方法,如果您专门寻找 Context.

,则首选这些方法