The Fragment Lifecycle Methods
Fragments have lifecycle methods, just like activities do. In fact, they support most of the same lifecycle methods as activities:
onCreate()
-
onStart()
(but notonRestart()
) onResume()
onPause()
onStop()
onDestroy()
By and large, the same rules apply for fragments as do for activities with respect to these lifecycle methods (e.g., onDestroy()
may not be called).
In addition to those and the onCreateView()
method we examined earlier in this chapter, there are other lifecycle methods that you can elect to override if you so choose.
onAttach()
will be called first, even before onCreate()
, letting you know that your fragment has been attached to an activity. You are passed the Activity
that will host your fragment.
onViewCreated()
will be called after onCreateView()
. This is particularly useful if you are inheriting the onCreateView()
implementation but need to configure the resulting views. For example, you need to attach an adapter to a ListFragment
— a common place to do that is in onViewCreated()
, as you know that the ListView
is set up at that time.
onActivityCreated()
will be called to indicate that the activity’s onCreate()
has completed. If there is something that you need to initialize in your fragment that depends upon the activity’s onCreate()
having completed its work, you can use onActivityCreated()
for that initialization work.
onDestroyView()
is called before onDestroy()
. This is the counterpart to onCreateView()
where you set up your UI. If there are things that you need to clean up specific to your UI, you might put that logic in onDestroyView()
.
onDetach()
is called after onDestroy()
, to let you know that your fragment has been disassociated from its hosting activity.
Google offers this diagram, depicting the order in which these events will occur:
(the above image is reproduced from work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License)
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.