Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Android 9 Development Cookbook - Third Edition

You're reading from  Android 9 Development Cookbook - Third Edition

Product type Book
Published in Oct 2018
Publisher Packt
ISBN-13 9781788991216
Pages 464 pages
Edition 3rd Edition
Languages
Author (1):
Rick Boyer Rick Boyer
Profile icon Rick Boyer

Table of Contents (24) Chapters

Title Page
Copyright and Credits
Dedication
About Packt
Contributors
Preface
Activities Layouts Views, Widgets, and Styles Menus and Action Mode Fragments Home Screen Widgets, Search, and the System UI Data Storage Alerts and Notifications Using the Touchscreen and Sensors Graphics and Animation A First Look at OpenGL ES Multimedia Telephony, Networks, and the Web Location and Using Geofencing Getting Your App Ready for the Play Store Getting Started with Kotlin Other Books You May Enjoy Index

Chapter 5. Fragments

In this chapter, we will cover the following topics:

  • Creating and using a Fragment
  • Adding and removing Fragments during runtime
  • Passing data between Fragments
  • Handling the Fragment back stack

Introduction


With a firm understanding of layouts from Chapter 2, Layouts, we'll dig deeper into UI development with Fragments. Fragments are a way to separate your UI into smaller sections that can easily be reused. Think of Fragments as mini-activities, complete with their own classes, layouts, and life cycle. Instead of designing your screen in one Activity Layout, possibly duplicating functionality across multiple layouts, you can break the screen into smaller, logical sections and turn them into Fragments. Your Activity Layout can then reference one or multiple Fragments, as needed.

Creating and using a Fragment


Android didn't always support Fragments. The early versions of Android were designed for phones when screens had relatively small displays. It wasn't until Android started being used on tablets that there was a need to split the screen into smaller sections. Android 3.0 introduced the Fragments class and the Fragment Manager.

Along with a new class, also came the Fragment Lifecycle. The Fragment Lifecycle is similar to the Activity Lifecycle introduced in Chapter 1, Activities, as most events parallel the Activity Lifecycle.

Here's a brief overview of the main callbacks:

  • onAttach(): It's called when the Fragment is associated with an Activity.
  • onCreate(): It's called when the Fragment is first created.
  • onCreateView(): It's called when the Fragment is about to be displayed for the first time.
  • onActivityCreated(): It's called when the associated Activity is created.
  • onStart(): It's called when the Fragment will become visible to the user.
  • onResume(): It's called just...

Adding and removing Fragments during runtime


Defining a Fragment in the layout, as we did in the previous recipe, is known as a static Fragment, which doesn't allow the fragment to be changed during runtime. Rather than using the <fragment> element, we will create a container to hold the Fragment, then create the Fragment dynamically in the Activity's onCreate() method.

The FragmentManager provides the APIs for adding, removing, and changing Fragments during runtime using a FragmentTransaction. A Fragment transaction consists of the following:

  1. Starting a transaction
  2. Performing one or multiple actions
  3. Committing the transaction

This recipe will demonstrate the Fragment Manager by adding and removing Fragments during runtime.

Getting ready

Create a new project in Android Studio and call it: RuntimeFragments. Use the default Phone & Tablet option and select Empty Activity on the Add an Activity to Mobile dialog.

How to do it...

To demonstrate adding and removing Fragments, we first need to...

Passing data between Fragments


Often, the need arises to pass information between Fragments. An email application serves as a classic example. It's common to have the list of emails in one Fragment and show the email details in another Fragment (this is commonly referred to as a Master/Detail pattern). Fragments make creating this pattern easier because we only have to code each Fragment once, then include them in different layouts. We can easily have a single Fragment in a portrait layout with the ability to swap out the master Fragment with the detail Fragment when an email is selected. We can also create a two-panel layout where both the list and detail Fragments are side by side. Either way, when the user clicks the email in the list, the email opens up in the detail panel. This is when we need to communicate between two Fragments.

Since one of the primary goals of Fragments is that they be completely self-contained, direct communication between Fragments is discouraged, and for good...

Handling the Fragment back stack


In several of the previous recipes, it was mentioned that you should call the addToBackStack() method in the Fragment transaction to enable Android to maintain a Fragment back stack. This is the first step, but may not be enough to provide a rich user experience. In this recipe, we'll explore two other callbacks: onBackPressed() and onBackStackChanged(). As you'll see, by implementing these callbacks, your application can provide specific behavior for the Fragment back stack. The onBackPressed() callback allows the app to check the back stack state and provide custom behavior, such as closing the app when appropriate.

The onBackStackChanged() callback is called whenever the actual back stack changes - such as when a Fragment is popped from the back stack. By overriding this callback, your app can check the current Fragment and update the UI (such as the Home key back arrow) as appropriate.

Getting ready

Create a new project in Android Studio and call it FragmentBackStack...

lock icon The rest of the chapter is locked
You have been reading a chapter from
Android 9 Development Cookbook - Third Edition
Published in: Oct 2018 Publisher: Packt ISBN-13: 9781788991216
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime}