Chapter 8. Nested Fragments: Dealing with Children

image with no caption

You’ve seen how using fragments in activities allow you to reuse code and make your apps more flexible.

In this chapter, we’re going to show you how to nest one fragment inside another. You’ll see how to use the child fragment manager to tame unruly fragment transactions. Along the way you’ll see why knowing the differences between activities and fragments is so important.

Creating nested fragments

In Chapter 7, you saw how to create fragments, how to include them in activities, and how to connect them together. To do this, we created a list fragment displaying a list of workouts, and a fragment displaying details of a single workout.

It’s not just activities that can contain fragments—fragments can be nested inside other fragments. So that you can see this in action, we’re going to add a stopwatch fragment to our workout detail fragment.

image with no caption

We’ll add a new stopwatch fragment

We’re going to add a new stopwatch fragment called StopwatchFragment.java that uses a layout called fragment_stopwatch.xml. We’re going to base the fragment on the stopwatch activity we created back in Chapter 4.

We already know that activities and fragments behave in similar ways, but we also know that a fragment is a distinct type of object—a fragment is not a subclass ...

Get Head First Android Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.