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


Retaining a fragment


Fortunately, fragments have a feature that you can use to keep the BeatBox instance alive across a
configuration change: retainInstance. Within your override of BeatBoxFragment.onCreate(...), set a
property on the fragment.


Listing 21.18  Calling setRetainInstance(true) (BeatBoxFragment.java)


public static BeatBoxFragment newInstance() {
return new BeatBoxFragment();
}


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);


mBeatBox = new BeatBox(getActivity());
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {


By default, the retainInstance property of a fragment is false. This means it is not retained,
but is destroyed and re-created on rotation along with the activity that hosts it. Calling
setRetainInstance(true) retains the fragment. When a fragment is retained, the fragment is not
destroyed with the activity. Instead, it is preserved and passed along intact to the new activity.


When you retain a fragment, you can count on all of its instance variables (like mBeatBox) to keep the
same values. When you reach for them, they are simply there.


Run BeatBox again. Play the 69_ohm-loko sound, rotate the device, and confirm that playback
continues unimpeded.


Rotation and retained fragments


Let’s take a closer look at how retained fragments work. Retained fragments take advantage of the fact
that a fragment’s view can be destroyed and re-created without having to destroy the fragment itself.


During a configuration change, the FragmentManager first destroys the views of the fragments in
its list. Fragment views always get destroyed and re-created on a configuration change for the same
reasons that activity views are destroyed and re-created: If you have a new configuration, then you
might need new resources. Just in case better matching resources are now available, you rebuild the
view from scratch.


Next, the FragmentManager checks the retainInstance property of each fragment. If it is false,
which it is by default, then the FragmentManager destroys the fragment instance. The fragment
and its view will be re-created by the new FragmentManager of the new activity “on the other side”
(Figure 21.9).

Free download pdf