Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1

Chapter 21  Unit Testing and Audio Playback


A retained fragment is not destroyed, but it is detached from the dying activity. This puts the fragment
in a retained state. The fragment still exists, but it is not hosted by any activity (Figure 21.11).


Figure 21.11  Fragment lifecycle


The retained state is only entered into when two conditions are met:



  • setRetainInstance(true) has been called on the fragment

  • the hosting activity is being destroyed for a configuration change (typically rotation)


A fragment is only in the retained state for an extremely brief interval – the time between being
detached from the old activity and being reattached to the new activity that is immediately created.


For the More Curious: Whether to Retain


Retained fragments: pretty nifty, right? Yes! They are indeed nifty. They appear to solve all the
problems that pop up from activities and fragments being destroyed on rotation. When the device
configuration changes, you get the most appropriate resources by creating a brand-new view, and you
have an easy way to retain data and objects.

Free download pdf