Reader small image

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

Product typeBook
Published inMay 2023
PublisherPackt
ISBN-139781837634934
Edition2nd Edition
Right arrow
Authors (4):
Alex Forrester
Alex Forrester
author image
Alex Forrester

Alex Forrester is an experienced software developer with more than 20 years of experience in mobile, web development, and content management systems. He has been working with Android for over 8 years, creating flagship apps for blue-chip companies across a broad range of industries at Sky, The Automobile Association, HSBC, The Discovery Channel, and O2. Alex lives in Hertfordshire with his wife and daughter. When he's not developing, he likes rugby and running in the Chiltern hills.
Read more about Alex Forrester

Eran Boudjnah
Eran Boudjnah
author image
Eran Boudjnah

Eran Boudjnah is a developer with over 20 years of experience in developing desktop applications, websites, interactive attractions, and mobile applications. He has been working with Android for about 7 years, developing apps and leading mobile teams for a wide range of clients, from start-ups (JustEat) to large-scale companies (Sky) and conglomerates. He is passionate about board games (with a modest collection of a few hundred games) and has a Transformers collection he's quite proud of. Eran lives in North London with Lea, his wife.
Read more about Eran Boudjnah

Alexandru Dumbravan
Alexandru Dumbravan
author image
Alexandru Dumbravan

Alexandru Dumbravan has been an Android Developer since 2011 and worked across a variety of Android applications which contained features such as messaging, voice calls, file management, and location. He continues to broaden his development skills while working in London for a popular fintech company.
Read more about Alexandru Dumbravan

Jomar Tigcal
Jomar Tigcal
author image
Jomar Tigcal

Jomar Tigcal is an Android developer with over 10 years of experience in mobile and software development. He worked on various stages of app development for small startups to large companies. Jomar has also given talks and conducted training and workshops on Android. In his free time, he likes running and reading. He lives in Vancouver, Canada with his wife Celine.
Read more about Jomar Tigcal

View More author details
Right arrow

Developing the UI with Fragments

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.

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, which 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...

Technical requirements

The complete code for all the exercises and the activity in this chapter is available on GitHub at https://packt.link/KmdBZ

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, the running state, and destruction that configure the initialization, display, and cleanup. Fragments run in an activity, and a 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.

The same steps are gone through to initialize the fragment and prepare for it to be displayed to the user before being available...

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. You can also 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 a larger size 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 two panes (dual-pane layouts) can be supported. This also provides...

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 ViewGroup as a container for fragments and then adding, replacing, and removing fragments from 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 three or four 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...

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 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.

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 destinations...

Summary

This chapter has covered fragments in depth, starting with learning about 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 the UI display and logic can be self-contained in individual fragments. Other options for how to add fragments to an app using a FragmentContainerView 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 about here will allow you to build upon them and progress to create increasingly more advanced apps. Fragments are at the core of building effective navigation into your apps in order to bind features and functionality that are simple and easy to use.

The next chapter will explore this area in detail by using established...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
How to Build Android Apps with Kotlin - Second Edition
Published in: May 2023Publisher: PacktISBN-13: 9781837634934
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.
undefined
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 $15.99/month. Cancel anytime

Authors (4)

author image
Alex Forrester

Alex Forrester is an experienced software developer with more than 20 years of experience in mobile, web development, and content management systems. He has been working with Android for over 8 years, creating flagship apps for blue-chip companies across a broad range of industries at Sky, The Automobile Association, HSBC, The Discovery Channel, and O2. Alex lives in Hertfordshire with his wife and daughter. When he's not developing, he likes rugby and running in the Chiltern hills.
Read more about Alex Forrester

author image
Eran Boudjnah

Eran Boudjnah is a developer with over 20 years of experience in developing desktop applications, websites, interactive attractions, and mobile applications. He has been working with Android for about 7 years, developing apps and leading mobile teams for a wide range of clients, from start-ups (JustEat) to large-scale companies (Sky) and conglomerates. He is passionate about board games (with a modest collection of a few hundred games) and has a Transformers collection he's quite proud of. Eran lives in North London with Lea, his wife.
Read more about Eran Boudjnah

author image
Alexandru Dumbravan

Alexandru Dumbravan has been an Android Developer since 2011 and worked across a variety of Android applications which contained features such as messaging, voice calls, file management, and location. He continues to broaden his development skills while working in London for a popular fintech company.
Read more about Alexandru Dumbravan

author image
Jomar Tigcal

Jomar Tigcal is an Android developer with over 10 years of experience in mobile and software development. He worked on various stages of app development for small startups to large companies. Jomar has also given talks and conducted training and workshops on Android. In his free time, he likes running and reading. He lives in Vancouver, Canada with his wife Celine.
Read more about Jomar Tigcal