March 20, 2015

Android Trivia: Differences between the Activity and the Fragment Lifecycle




Imagine that you are going from Activity A to Activity B (via startActivity).

Imagine than after it, on Activity B you replace Fragment A for Fragment B.

Most developers when starting  imagine a very similar lifecycle between the 2 operations, due to the similar method names.


Well...


Activities

A -> B

Activity A: onCreate
Activity A: onCreate
Activity A: onStart
Activity A: onPostCreate
Activity A: onResume
Activity A: onResumeFragments
Activity A: onPostResume
Activity A: onPause
Activity A: onResume
Activity A: onResumeFragments
Activity A: onPostResume
Activity A: onPause
Activity B: onCreate
Activity B: onAttachFragment
Activity B: onStart
Activity B: onPostCreate
Activity B: onResume
Activity B: onResumeFragments
Activity B: onAttachFragment
Activity B: onPostResume

B -> A

Activity A: onStop
Activity A: onDestroy
...
Fragments

A -> B 

Fragment A: Attaching.
Fragment A: onCreate
Fragment A: onResume
Fragment A: onPause
Fragment A: onStop
Fragment A: onDestroyView
Fragment B: Attaching.
Fragment B: onCreate
Fragment B: onResume
Fragment B: onPause
Fragment B: onStop
Fragment B: onDestroyView
Fragment B: onDestroy
Fragment B: Detaching.







B -> A

Fragment A: onResume
...




Don't miss the overlap on the Activities and the lack of it on the Fragments, or you may develop some code that doesn't work as you except.