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

旧城冷巷雨未停 提交于 2021-01-27 03:54:21

问题


I have two ViewModels. One is used from the Fragment only and the other one is a shared ViewModel from the Activity.

Fragment:

@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);
}

But in order to know if I can use the content from the activity's ViewModel, I need to know if the onActivityCreated(...) is called after onViewCreated(...) so I can request my data in the Fragment ViewModel based on data I have in the Activity's ViewModel.

To summarise:

Is it for certain that onActivityCreated(...) is called after onViewCreated(...) has finished?


回答1:


After some further research I think I found the answer.

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

Based on the documentation:

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

The view hierarchy should be fully instantiated and therefore onActivityCreated will be called after the completion of onViewCreated




回答2:


Yes, it is for certain, as you found out. Also, see this answer for a cute little lifecycle drawing (the second one).



来源:https://stackoverflow.com/questions/56260090/is-onactivitycreated-called-after-onviewcreated-in-a-fragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!