Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Fragment onCreateView vs. onActivityCreated

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?

like image 866
gordonwd Avatar asked Nov 07 '11 19:11

gordonwd


People also ask

What are the differences between onCreate () onCreateView () and onActivityCreated () in fragments and what would they each be used for?

The onCreate() is called first, for doing any non-graphical initialisations. Next, you can assign and declare any View variables you want to use in onCreateView() . Afterwards, use onActivityCreated() to do any final initialisations you want to do once everything has completed.

Why onActivityCreated is now deprecated in fragment?

Need for onActivityCreated() deprecation In such similar fashion android developers saw the tight coupling of code dependent to the Activity's life cycle. And they decided that it is not a good practice anymore to be dependent on the activity attach to do certain things inside the fragment.

What is the difference between onCreateView and onViewCreated in fragment?

onCreateView() is called by Android once the Fragment should inflate a view. onViewCreated() is called after onCreateView() and ensures that the fragment's root view is non-null .


1 Answers

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.

like image 188
vitakot Avatar answered Oct 04 '22 13:10

vitakot