Introducing Fragments

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

A fragment is a controller object that an activity can deputize to perform tasks. Most commonly, the task is managing a UI. The UI can be an entire screen or just one part of the screen.

A fragment managing a UI is known as a UI fragment. A UI fragment has a view of its own that is inflated from a 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’s view can hold a container for the fragment. The fragment’s view is inserted into the container once it is inflated. In this chapter, the activity will host a single fragment, but an activity can have multiple containers in its view for different fragments.

You can use the fragment (or fragments) associated with the activity to compose and recompose the screen as your app and users require. The activity’s view technically stays the same throughout its lifetime, and no laws of Android are violated.

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; the activity will replace the detail fragment with another detail fragment (Figure 8.3). No activities need to die for this major view change to happen.

Figure 8.3  Swapping out a detail fragment

Swapping out a detail fragment

Using UI 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
18.117.196.217