75

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?

zpea
  • 1,072
  • 6
  • 23
gordonwd
  • 4,537
  • 9
  • 37
  • 53

2 Answers2

77

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.

vitakot
  • 3,786
  • 4
  • 27
  • 59
  • Why its not required in case of 'static'? It seems everyone got this but i didnt. – Diffy Jan 22 '15 at 11:33
  • 6
    Don't think everyone got it, Diffy, but they were just happy with the answer :) – Boy Feb 20 '15 at 17:38
  • 7
    @Diffy, he meant by static view that the view which is displayed to the user is nothing but the inflated xml layout. No modification in coding or at runtime. – Hamzeh Soboh Jul 29 '15 at 09:46
  • 3
    @vitakot Can you elaborate a little more the list from the adapter use case. Why can't you put in onCreateView? – lujop Oct 03 '16 at 11:05
  • 1
    Great Answer but it be more helpful if you can @vitakot explain why we need to use onActivityCreated method when filling in data into the listview/reyclerview from adapters. – user3189761 Apr 25 '20 at 10:36
3

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.