Sobes.tech
Junior

What is the lifecycle of a fragment in Android?

sobes.tech AI

Answer from AI

The lifecycle of a fragment is closely related to the lifecycle of the activity to which it is attached.

Main states and corresponding callback methods:

  • onAttach(): The fragment is attached to an activity.
  • onCreate(): The fragment is created.
  • onCreateView(): The fragment's view hierarchy is created.
  • onViewCreated(): The view hierarchy is created, views are available.
  • onActivityCreated(): The activity containing the fragment is created.
  • onStart(): The fragment becomes visible to the user.
  • onResume(): The fragment becomes active and gains user focus.
  • onPause(): The fragment loses focus but is still visible.
  • onStop(): The fragment becomes invisible.
  • onDestroyView(): The fragment's view hierarchy is destroyed.
  • onDestroy(): The fragment is destroyed.
  • onDetach(): The fragment is detached from the activity.

Transition diagram:

onAttach() -> onCreate() -> onCreateView() -> onViewCreated() -> onActivityCreated() -> onStart() -> onResume()
onResume() -> onPause() -> onStop() -> onDestroyView() -> onDestroy() -> onDetach()
onStart() -> onStop() -> onDestroyView() -> onDestroy() -> onDetach()
onPause() -> onResume()
onStop() -> onRestart() (not directly for fragment) -> onStart()
What is the lifecycle of a fragment in Android… - sobes.tech