A fragment typically represents a reusable portion of an Activity
’s user interface, but may also represent reusable program logic. This app uses fragments to create and manage portions of the app’s GUI. You can combine several fragments to create user interfaces that take advantage of tablet screen sizes. You also can easily interchange fragments to make your GUIs more dynamic—you’ll learn about this in Chapter 8.
Fragment (package android.app
) is the base class of all fragments. The Flag Quiz app defines the following direct and indirect Fragment
subclasses:
• Class QuizFragment
(Section 5.6)—a direct subclass of Fragment
—displays the quiz’s GUI and defines the quiz’s logic. Like an Activity
, each Fragment
has its own layout that’s typically defined as a layout resource, but can be created dynamically. In Section 5.4.8, you’ll build QuizFragment
’s GUI. You’ll use the QuizFragment
in MainActivity
’s layouts—one for devices in portrait orientation and one for tablet devices in landscape orientation.
• Class SettingsFragment
(Section 5.7) is a subclass of PreferenceFragment (package android.preference), which can automatically maintain an app’s user preferences in a SharedPreferences
file on the device. As you’ll see, you can create an XML file that describes the user preferences and class PreferenceFragment
can use that XML file to build an appropriate preferences GUI (Figs. 5.3–5.4).
• When you finish a quiz, the QuizFragment
creates an anonymous inner class that extends DialogFragment (package android.app
) and uses it to display an AlertDialog
containing the quiz results (Section 5.6.9).
Fragment
s must be hosted by an Activity
—they cannot execute independently. When this app runs in landscape orientation on a tablet, the MainActivity
hosts all of the Fragment
s. In portrait orientation (on any device), the SettingsActivity
(Section 5.8) hosts the SettingsFragment
and the MainActivity
hosts the others.
Though Fragment
s were introduced in Android 3.0, Fragment
s and other more recent Android features can be used in earlier versions via the Android Support Library. For more information, visit:
3.129.25.217