Activity onStart() 在 Fragment 的 onActivityCreated() 之前被调用

Activity onStart() being called before Fragment's onActivityCreated()

我遇到一个问题,我的片段的 onActivityCreated() 方法在我的 activity 的 onStart() 方法被调用之后被调用。这似乎暗示我的 activity 的 onCreate() 方法在 onStart() 之后完成?不会吧……可以吗?在我的 activity 的生命周期中什么时候调用片段的 onActivityCreated()?此外,如果我有多个片段,如何控制片段的 onActivityCreated() 调用顺序?

在我的 activity:

@Override
protected void onStart() {
    super.onStart();
    methodA(); // this is called ...
}

在我的片段中:

    @Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    methodB(); // ... before this
}

onActivityCreated() method is being called after my activity's onStart() method is called

请记住,onActivityCreated() 方法只是 activity.

片段的回调

This seems to imply that my activity's onCreate() method is finishing after onStart()? That can't be the case ... can it?

错了! Activity和fragment是分开的,所以Activity中的onCreated()方法和Activity中的onActivityCreated()方法片段不能相同。如上,在 Fragment 中它只是一个带有 activity state.

的回调映射

让我们看一下这张照片,以便更好地理解。

在 Google 的官方文档中: Activity onStart()

Called just before the activity becomes visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.

片段回调:onActivityCreated()

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).

最后一个:

Furthermore, if I have multiple fragments, how can I control the order of the fragments' onActivityCreated() calls?

这取决于您将片段添加到 activity 的方式。基本上顺序将是添加片段的顺序。