Android Fragment onCreateView vs. onActivityCreated

AndroidAndroid FragmentsLifecycleAndroid ActivityAndroid Lifecycle

Android Problem Overview


I know that a fragment's view hierarchy has to be inflated in onCreateView, but what other functionality can be in onCreateView vs. what should wait for onActivityCreated? My current implementation uses separate activities for everything, and a typical activity does most of its work in its onCreate method, including inflating the view, setting the content view, initializing the various widgets with data, setting up listeners, etc.

So can this probably all be moved into onCreateView, or should some functions be put into an onActivityCreated method instead?

Android Solutions


Solution 1 - Android

If your view is static, then moving any code to the onActivityCreated method is not necessary. But when you - for instance, fill some lists from the adapter, then you should do it in the onActivityCreated method as well as restoring the view state when setRetainInstance used to do so.

Also accessing the view hierarchy of the parent activity must be done in the onActivityCreated, not sooner.

Solution 2 - Android

onActivityCreated() is deprecated in fragment 1.3.0-alpha02 and there is a recommendation to use onViewCreated() instead. View is already created here and you can set listeners, observe LiveData from ViewModel, initialize recyclerView, etc.

For a better understanding, you can take a look at my blog post, where I describe the Android Fragment lifecycle in 137 seconds.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongordonwdView Question on Stackoverflow
Solution 1 - AndroidvitakotView Answer on Stackoverflow
Solution 2 - Androidvladsonkin.comView Answer on Stackoverflow