Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
How to Build Android Apps with Kotlin

You're reading from  How to Build Android Apps with Kotlin

Product type Book
Published in Feb 2021
Publisher Packt
ISBN-13 9781838984113
Pages 794 pages
Edition 1st Edition
Languages
Authors (4):
Alex Forrester Alex Forrester
Profile icon Alex Forrester
Eran Boudjnah Eran Boudjnah
Profile icon Eran Boudjnah
Alexandru Dumbravan Alexandru Dumbravan
Profile icon Alexandru Dumbravan
Jomar Tigcal Jomar Tigcal
Profile icon Jomar Tigcal
View More author details

Table of Contents (17) Chapters

Preface
1. Creating Your First App 2. Building User Screen Flows 3. Developing the UI with Fragments 4. Building App Navigation 5. Essential Libraries: Retrofit, Moshi, and Glide 6. RecyclerView 7. Android Permissions and Google Maps 8. Services, WorkManager, and Notifications 9. Unit Tests and Integration Tests with JUnit, Mockito, and Espresso 10. Android Architecture Components 11. Persisting Data 12. Dependency Injection with Dagger and Koin 13. RxJava and Coroutines 14. Architecture Patterns 15. Animations and Transitions with CoordinatorLayout and MotionLayout 16. Launching Your App on Google Play

3. Developing the UI with Fragments

Overview

This chapter covers fragments and the fragment lifecycle. It demonstrates how to use them to build efficient and dynamic layouts that respond to different screen sizes and configurations, and allow you to divide your UI into different sections. By the end of this chapter, you will be able to create static and dynamic fragments, pass data to and from fragments and activities, and use the Jetpack Navigation component to detail how fragments fit together.

Introduction

In the previous chapter, we explored the Android Activity Lifecycle and looked into how it is used in apps to navigate between screens. We also analyzed various types of launch modes that defined how transitioning between screens happened. In this chapter, you'll explore fragments. A fragment is a section, portion, or, as the name implies, fragment of an Android activity.

Throughout the chapter, you'll learn how to use fragments, see how they can exist in more than one activity, and discover how multiple fragments can be used in one activity. You'll start by adding simple fragments to an activity and then progress to learning about the difference between static and dynamic fragments. Fragments can be used to simplify creating layouts for Android tablets that have larger form factors using dual-pane layouts. For example, if you have an average-sized phone screen and you want to include a list of news stories, you might only have enough space to display...

The Fragment Lifecycle

A fragment is a component with its own lifecycle. Understanding the fragment lifecycle is critical as it provides callbacks at certain stages of fragment creation, running state, and destruction where you can configure the initialization, display, and cleanup. Fragments run in an activity, and the fragment's lifecycle is bound to the activity's lifecycle.

In many ways, the fragment lifecycle is very similar to the activity lifecycle, and at first glance, it appears that the former replicates the latter. There are as many callbacks that are the same or similar in the fragment lifecycle as there are in the activity lifecycle, such as onCreate(savedInstanceState: Bundle?).

The fragment lifecycle is tied to the activity lifecycle, so wherever fragments are used, the fragment callbacks are interleaved with the activity callbacks.

Note

The full sequence of the interaction between fragments and activities is illustrated in the official docs:...

Static Fragments and Dual-Pane Layouts

The previous exercise introduced you to static fragments, those that can be defined in the activity XML layout file. One of the advantages of the Android development environment is the ability to create different layouts and resources for different screen sizes. This is used for deciding which resources to display depending on whether the device is a phone or a tablet. The space for laying out UI elements can increase substantially with the larger size of a tablet. Android allows specifying different resources depending on many different form factors. The qualifier frequently used to define a tablet in the res (resources) folder is sw600dp. This states that if the shortest width (sw) of the device is over 600 dp, then use these resources. This qualifier is used for 7" tablets and larger. Tablets facilitate what is known as dual-pane layouts. A pane represents a self-contained part of the user interface. If the screen is large enough, then...

Dynamic Fragments

So far, you've only seen fragments added in XML at compile time. Although this can satisfy many use cases, you might want to add fragments dynamically at runtime to respond to the user's actions. This can be achieved by adding a ViewGroup as a container for fragments and then adding, replacing, and removing fragments from the ViewGroup. This technique is more flexible as the fragments can be active until they are no longer needed and then removed instead of always being inflated in XML layouts as you have seen with static fragments. If 3 or 4 more fragments are required to fulfill separate user journeys in one activity, then the preferred option is to react to the user's interaction in the UI by adding/replacing fragments dynamically. Using static fragments works better when the user's interaction with the UI is fixed at compile time and you know in advance how many fragments you need. For example, this would be the case for selecting items from...

Jetpack Navigation

Using dynamic and static fragments, although very flexible, introduces a lot of boilerplate code into your app and can become quite complicated when user journeys require adding, removing, and replacing multiple fragments while managing the back stack. Google introduced the Jetpack components, as you learned in Chapter 1, Creating Your First App, to use established best practices in your code. The Navigation component within the suite of Jetpack components enables you to reduce boilerplate code and simplify navigation within your app. We are going to use it now to update the Star Sign app to use this component.

Exercise 3.05: Adding a Jetpack Navigation Graph

In this exercise, we are going to reuse most of the classes and resources from the last exercise. We will first create an empty project and copy the resources. Next, we will add the dependencies and create a navigation graph. Using a step-by-step approach, we will configure the navigation graph and add...

Summary

This chapter has covered fragments in depth, starting with learning the fragment lifecycle and the key functions to override in your own fragments. We then moved on to adding simple fragments statically to an app in XML and demonstrating how UI display and logic can be self-contained in individual fragments. Other options for how to add fragments to an app using a ViewGroup and dynamically adding and replacing fragments were then covered. We then finished with how this can be simplified by using the Jetpack Navigation component.

Fragments are one of the fundamental building blocks of Android development. The concepts you have learned here will allow you to build upon and progress to creating increasingly more advanced apps. Fragments are at the core of building effective navigation into your app in order to bind features and functionality that is simple and easy to use. The next chapter will explore this area in detail by using established UI patterns to build clear and...

lock icon The rest of the chapter is locked
You have been reading a chapter from
How to Build Android Apps with Kotlin
Published in: Feb 2021 Publisher: Packt ISBN-13: 9781838984113
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}