Reputation: 1226
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:
Activity: onCreate
Activity: onStart
Fragment: onAttach
Fragment: onCreate
Fragment: onCreateView
Fragment: onViewCreated
Fragment: onActivityCreated
Activity: onResume
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:
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).
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
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.
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