onActivityCreated() 是在片段中的 onViewCreated() 之后调用的吗?

Is onActivityCreated() called after onViewCreated() in a Fragment?

我有两个 ViewModel。一个仅在 Fragment 中使用,另一个是来自 Activity.

的共享 ViewModel

片段:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    viewModel = ViewModelProviders.of(this).get(FragmentViewModel.class);
    ...
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    activityViewModel = ViewModelProviders.of(getActivity()).get(ActivityViewModel.class);
}

但是为了知道我是否可以使用 activity 的 ViewModel 中的 content,我需要知道 onActivityCreated(...) 是否被调用在 onViewCreated(...) 之后,我可以根据 Activity 的 ViewModel 中的数据在 Fragment ViewModel 中请求我的数据。

总结一下:

确定onActivityCreated(...)是在onViewCreated(...)结束后调用的吗?

是的,这是肯定的,正如您所发现的。另外,请参阅 可爱的生命周期小图(第二张)。

经过进一步研究,我想我找到了答案。

onActivityCreated added in version 22.1.0 void onActivityCreated (Bundle savedInstanceState)

Called when the fragment's activity has been created and this fragment's view hierarchy instantiated. It can be used to do final initialization once these pieces are in place, such as retrieving views or restoring state. It is also useful for fragments that use setRetainInstance(boolean) to retain their instance, as this callback tells the fragment when it is fully associated with the new activity instance. This is called after onCreateView(LayoutInflater, ViewGroup, Bundle) and before onViewStateRestored(Bundle).

基于文档:

..fragment's view hierarchy instantiated. It can be used to do final initialization once these pieces are in place..

视图层次结构应完全实例化,因此 onActivityCreated 将在 onViewCreated

完成后调用

更新

信息:onActivityCreated 现已弃用

use onViewCreated(View, Bundle) for code touching the Fragment's view and onCreate(Bundle) for other initialization. To get a callback specifically when a Fragment activity's Activity.onCreate(Bundle) is called, register a androidx.lifecycle.LifecycleObserver on the Activity's Lifecycle in onAttach(Context), removing it when it receives the Lifecycle.State.CREATED callback.