FRAGMENTS

The previous section showed you what an activity is. In a small-screen device (such as a smartphone), an activity typically fills up an entire screen, displaying the various views that make up the user interface of an application. The activity is essentially a container for views. However, when an activity is displayed in a large-screen device, such as on a tablet, it is somewhat out of place. Suddenly, the screen becomes much bigger and all the views in an activity must be arranged to make full use of the bigger screen, resulting in complex changes to the view hierarchy. A better approach would be to have “mini-activities,” each containing its own set of views. During runtime, an activity can contain one or more of these “mini-activities,” depending on the screen orientation in which the device is held. In Android 3.0, these “mini-activities” are known as fragments.

Think of a fragment as another form of activity. You create fragments to contain views, just like activities. Fragments are always embedded in an activity. A good way to imagine a fragment is to look at Figure 2-6. Here, you have two fragments. Fragment 1 may contain a ListView showing a list of book titles. Fragment 2 may contain some TextViews and ImageViews showing some text and images.

Now, imagine the application is running on an Android tablet in portrait mode (or on an Android smartphone). ...

Get Beginning Android now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.