KirstenLy
KirstenLy

Reputation: 1226

Questions about Activity and Fragment lifecycle

I trace lifecycle method's callback from Activity and Fragment components and i have a lot of questions. I need you help to understand some points.

Situation 1:

One launcher Activity with one Fragment, which filled it. When app started, Fragment become active and user see only Fragment.

Lyfecycle:

  1. Activity: onCreate

  2. Activity: onStart

  3. Fragment: onAttach

  4. Fragment: onCreate

  5. Fragment: onCreateView

  6. Fragment: onViewCreated

  7. Fragment: onActivityCreated

  8. Activity: onResume

  9. Fragment: onResume.

Questions:

1) There is no onResume between 2 - 3, because of Activity lose focus?

2) I don't think i understand what happen on 8 - 9. It seems like some kind of "switch focus" between Fragment and Activity. Ok, i can understand: 9 is about Fragment came to the foreground, take focus and onResume was called. But what is 8? When i load Fragment(since 3), Activity is never on foreground.

Situation 2:

Like situation 1, but now Fragment and Activity loaded and i pressed Home:

  1. Activity: onPause
  2. Fragment: onPause
  3. Activity: onStop
  4. Fragment: onStop

Questions:

When i run it, i expect another behavior. I thought Fragment should be the first who called stop methods, like (Fragment onPause -> Fragment onStop - > Activity methods). Why it worked this way?

Situation 3:

Like situation 2, Activity with Fragment are back to the foreground. I remember, they both have Stopped status (because of onStop was called).

  1. Activity: onStart
  2. Activity: onResume
  3. Fragment: onResume

Questions:

I expect 1-2, but i expect that Fragment call onStart, because, if i understand it correct, onStart called when fragment become visible. Why onStart was't called?

Upvotes: 0

Views: 1068

Answers (1)

farhanjk
farhanjk

Reputation: 1762

Fragment and Activity lifecycles work in parallel. The linear dependence between their lifecycle ends as soon as both activity and fragment are created.

The following figure explains how the two lifecycles are interconnected.

enter image description here

Note that onStart and onResume (and similarly, onStop and onPause) for both fragment and activity execute in parallel and there is no guarantee of order. Sometimes fragment will take precedence over activity, and vice versa.

The only guarantee is that activity's onCreate will always be called first. After that, fragment acts on its own.

Upvotes: 4

Related Questions