Introducing Fragments

You can make your app’s UI more flexible by moving UI management from the activity to one or more fragments.

Similar to how you have used your activities so far, a Fragment has a view of its own, often defined in a separate layout file. The fragment’s view contains the interesting UI elements that the user wants to see and interact with.

Instead of containing the UI, the activity acts as a container for the fragment. The fragment’s view is inserted into the container once it is initialized. In this chapter, the activity will host a single fragment, but an activity can have multiple containers in its view for different fragments.

Fragments are designed to hold reusable chunks of the UI. You can use the fragment (or fragments) associated with the activity to compose and recompose the screen as your app and users require. There is only one Activity class responsible for displaying your app’s content, but it hands control over parts of the screen to its Fragments. Because of this, your activity will be much simpler and will not violate any Android laws.

Let’s see how this would work in a list-detail application to display the list and detail together. You would compose the activity’s view from a list fragment and a detail fragment. The detail view would show the details of the selected list item.

Selecting another item should display a new detail view. This is easy with fragments: Your app would replace the detail fragment with another detail fragment (Figure 9.3). No activities need to die for this major view change to happen.

Figure 9.3  Swapping out a detail fragment

Swapping out a detail fragment

Using fragments separates the UI of your app into building blocks, which is useful for more than just list-detail applications. Working with individual blocks, it is easy to build tab interfaces, tack on animated sidebars, and more. Additionally, some of the new Android Jetpack APIs, such as the navigation controller, work best with fragments. So using fragments sets you up to integrate nicely with Jetpack APIs.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset