Android UI How to - Life Cycle of a Fragment methods








When a fragment is being created, it goes through the following states:

  • onAttach()
  • onCreate()
  • onCreateView()
  • onActivityCreated()

When the fragment becomes visible, it goes through these states:

  • onStart()
  • onResume()

When the fragment goes into the background mode, it goes through these states:

  • onPause()
  • onStop()

When the fragment is destroyed (when the hosting activity is destroyed), it goes through the following states:

  • onPause()
  • onStop()
  • onDestroyView()
  • onDestroy()
  • onDetach()

You can restore an instance of a fragment using a Bundle object, in the following states:

  • onCreate()
  • onCreateView()
  • onActivityCreated()

We can save a fragment's state in the onSaveInstanceState() method.





Difference

Most of the states experienced by a fragment are similar to those of activities. A few new states are specific to fragments:

  • onAttached() is called when the fragment has been associated with the activity
  • onCreateView() is called to create the view for the fragment
  • onActivityCreated() is called when the activity's onCreate() method has been returned
  • onDestroyView() is called when the fragment's view is being removed
  • onDetach() is called when the fragment is detached from the activity