35

Exactly when is onAttach called during the Fragment-Activity lifecycles?

I am aware of the Fragment Life-Cycle but exactly when?

Is it when the fragment object is initiated or when fragment manager is called?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Ackman
  • 1,562
  • 6
  • 31
  • 54

2 Answers2

131

In activity the first method is onCreate. onCreate of activity add the fragment and in this moment onAttach is called. like in the picture

enter image description here

Ref: https://github.com/xxv/android-lifecycle

MSpeed
  • 8,153
  • 7
  • 49
  • 61
Lucas Ferraz
  • 4,112
  • 2
  • 18
  • 23
  • 2
    It would be nice to add onSaveInstaceState to the scheme – Defuera Jun 23 '16 at 10:45
  • 1
    Where would onViewCreated from fragment be in this scheme ? – Javier Delgado Feb 03 '17 at 10:08
  • 3
    This is a very old diagram. onFreeze() has been renamed to onSaveInstanceState() in Android 0.9 SDK Beta. See https://developer.android.com/sdk/OLD_RELEASENOTES.html – Alex Bravo Feb 14 '17 at 17:32
  • This flow is incomplete. Some events can halt the activity execution. For example, activity `onDestroy` will not be called if the system is running out of memory and kills the process. Activity `onStart` will not be called if you call finish from Activity onCreate. The edge cases in Fragments are even scarier, so I am not even diving into those... – Ilya Gazman Apr 14 '21 at 00:04
1

onAttach is called after Fragment is associated with its Activity.

http://developer.android.com/reference/android/app/Fragment.html#onAttach(android.content.Context)

Wilder Pereira
  • 2,249
  • 3
  • 21
  • 31