Junior
What is the lifecycle of a fragment in Android?
sobes.tech AI
Answer from AI
The fragment lifecycle includes the following states and corresponding callback methods:
onAttach(): Called when the fragment is attached to an activity.onCreate(): The fragment is created. Called afteronAttach().onCreateView(): The system calls this method when the fragment needs to create its user interface view.onViewCreated(): Called immediately afteronCreateView(), indicating that the view hierarchy has been created.onActivityCreated(): Called when the activity'sonCreate()method containing the fragment has finished.onStart(): The fragment becomes visible to the user.onResume(): The fragment becomes active and receives focus.onPause(): The system calls this method as part of the activity lifecycle when preparing to go to the background or become invisible.onStop(): The fragment is no longer visible to the user.onDestroyView(): Called when the view associated with the fragment is being cleaned up.onDestroy(): The fragment is destroyed.onDetach(): The fragment is detached from the activity.
The lifecycle diagram looks approximately like this:
+-----------------+ +-----------------+ +-----------------+ +-----------------+
| INSTANTIATED |----| ADDED |----| CREATED |----| STARTED |
+-----------------+ +-----------------+ +-----------------+ +-----------------+
| | | | |
| onAttach() | onAttach() | onCreate() | onStart() |
V V V V V
+-----------------+ +-----------------+ +-----------------+ +-----------------+
| ATTACHED |----| CREATED_VIEW |----| ACTIVITY |----| RESUMED |
+-----------------+ +-----------------+ +-----------------+ +-----------------+
| | | CREATED | |
| onCreateView() | onCreateView() | | onResume() |
V V V V V
+-----------------+ +-----------------+ +-----------------+ +-----------------+
| CREATED_VIEW |----| ACTIVITY |----| RESUMED |----| RESUMED |
+-----------------+ +-----------------+ +-----------------+ +-----------------+
| | CREATED | | |
| onViewCreated() | | | |
V V V V V
+-----------------+ +-----------------+ +-----------------+ +-----------------+
| ACTIVITY |----| RESUMED |----| RESUMED |----| RESUMED |
+-----------------+ +-----------------+ +-----------------+ +-----------------+
CREATED | | | |
| | | |
| onActivityCreated() | |
V V V V
+-----------------+ +-----------------+ +-----------------+ +-----------------+
| STARTED |----| RESUMED |----| RESUMED |----| RESUMED |
+-----------------+ +-----------------+ +-----------------+ +-----------------+
+-----------------+
| PAUSED |
+-----------------+
|
| onPause()
V
+-----------------+
| STOPPED |
+-----------------+
|
| onStop()
V
+-----------------+
| DESTROYED_VIEW |
+-----------------+
|
| onDestroyView()
V
+-----------------+
| DESTROYED |
+-----------------+
|
| onDestroy()
V
+-----------------+
| DETACHED |
+-----------------+
|
| onDetach()
V
+-----------------+
| INSTANTIATED |
+-----------------+