March 23, 2015

Android Trivia: Fragment Attachment



Imagine that:

You have a FragmentActivity which has a Drawer and the fragment attachment order was:

- Drawer
- Fragment A
- Fragment B.

Note: By order I mean that I'm adding the fragments on a list by the order that each is received on onAttachFragment. So when entering the Activity A, the order was the one above.


Imagine that you go to background, and you Activity A is killed, and when you reopen the app it restores its state. 

Do you know what the attachment order will be?

- Fragment A
- Fragment B
- Drawer


Yes. The Drawer will be the last. So if you are maintaining some of your own stack order using the Fragments lifecycle beware!






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.