• Meghan Gill

Fragment Lifecycle

Updated: Jul 23, 2021

The fragment lifecycle has 11 methods, many of which are shared with activities.


Lifecycle Methods Shared with Activities:


onCreate()

onStart()

onResume()

onPause()

onStop()

onDestroy()



These methods are called at roughly the same time as the activity's methods. So if an activity's onPause is called each fragment in that activity will receive a call to its onPause method as well.


 

Methods to handle interactions between fragments and the activity hosting them:


1. onAttach()


the first method in the fragment lifecycle. It's called when a fragment is first associated with an activity. getActivity() will return null if it is called before onAttach().



2. onCreateView()


is where we set up the view for our fragments. We inflate the view, do required set up then return the view.



3. onActivityCreated()


called when the activity's onCreate method has returned. If work needs to happen after the activity's view has been initialized but before the user sees the activity, it should be done here.



4. onDestroyView()


called when the fragment's view is being destroyed. If you need to clean up resources from the fragment's view it should be done here.



5. onDetach()


called when the fragment is being removed from the activity. After onDetach() is called any calls to getActivity() will return null.




99 views0 comments

Recent Posts

See All