LifeCycle
Fragment lifecycle is similar to Activity lifecycle
Lifecycle callbacks define how Fragment behaves in each state
States
Active(or Resumed)
Paused
Stopped
@Override onCreate(Bundle savedInstanceState)
:
System calls
onCreate()
when the Fragment is createdInitialize Fragment components and variables (preserved if the Fragment is paused and resumed)
Always include
super.onCreate(savedInstanceState)
in lifecycle callbacks
@Override onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
:
Inflate XML layout—required if Fragment has a UI
System calls this method to make Fragment visible
Must return the root
View
of Fragment layout or null if the Fragment does not have a UI
onActivityCreated()
: Called when the Activity onCreate() method has returned
Called after
onCreateView()
and beforeonViewStateRestored()
Retrieve views or restore state
Use
setRetainInstance()
to keep Fragment instance when Activity is recreated
Use onDestroyView()
to perform action after Fragment is no longer visible
Called after
onStop()
and beforeonDestroy()
View that was created in
onCreateView()
is destroyedA new View is created next time Fragment needs to be displayed
Activity Context
When Fragment is active or resumed:
Use
getActivity()
to get theActivity
that started the fragmentFind a View in the Activity layout:
Get Fragment by calling findFragmentById()
on FragmentManager
:
Add Fragment to back stack: addToBackStack(null)
Host
Activity
maintains back stack even afterFragment
is removedAllows navigation with Back button
Last updated