Reader small image

You're reading from  Android UI Development with Jetpack Compose - Second Edition

Product typeBook
Published inNov 2023
Reading LevelN/a
PublisherPackt
ISBN-139781837634255
Edition2nd Edition
Languages
Tools
Right arrow
Author (1)
Thomas Künneth
Thomas Künneth
author image
Thomas Künneth

Thomas Künneth is a Google Developer Expert for Android and has been a speaker and panelist at multiple international conferences about Android. Currently, Thomas works as a senior Android developer at Snapp Mobile. He has authored countless articles as well as one of the top-selling German Android books (currently in its sixth edition). He has also frequently contributed to various open source projects.
Read more about Thomas Künneth

Right arrow

Laying Out UI Elements in Compose

In the previous chapters, you learned how to build simple UIs. Although they consisted of just a few UI elements, they needed to arrange their buttons, text fields, and sliders in a particular order, direction, or hierarchy. Layouts position and size their content in a way specific to this layout, such as horizontally (Row()) or vertically (Column()). This chapter explores layouts in greater detail.

In this chapter, we will cover the following topics:

  • Using predefined layouts
  • Understanding the single measure pass
  • Creating custom layouts

We will start by exploring the predefined layouts of Row(), Column(), and Box(). You will learn how to combine them to create beautiful UIs. Next, I’ll introduce you to ConstraintLayout. It places composables that are relative to others on the screen and uses attributes to flatten the UI element hierarchy. This is an alternative to nesting Row(), Column(), and Box().

The second main...

Technical requirements

Please refer to the Technical requirements section of Chapter 1, Building Your First Compose App, for information about how to install and set up Android Studio, as well as how to get the sample apps. This chapter covers the ColumnWithTextsDemo, ConstraintLayoutDemo, CustomLayoutDemo, and PredefinedLayoutsDemo samples.

Using predefined layouts

When you create a UI, you must define where its elements appear and how big they are. Jetpack Compose provides a couple of basic layouts, which arrange their content along one main axis. There are three axes to consider:

  • Horizontal
  • Vertical
  • Stacked

Each axis is represented by a layout. Row() arranges its content horizontally, while Column() does so vertically. Box() and BoxWithConstraints() stack their contents on top of each other. By combining these axes-orientated building blocks, you can create great-looking UIs easily.

Combining basic building blocks

The following PredefinedLayoutsDemo sample app shows three checkboxes that toggle a red, a green, and a blue rectangle, respectively. The boxes appear only if the corresponding checkbox is checked:

Figure 4.1 – Sample PredefinedLayoutsDemo app

Figure 4.1 – Sample PredefinedLayoutsDemo app

Let’s see how this is done. First, I will show you how to create a checkbox with an accompanying...

Understanding the single measure pass

Laying out a UI element hierarchy means determining the sizes of all the elements and positioning them on the screen based on the layout strategy of their parent. At first, getting the size of, say, some text doesn’t sound too complicated. After all, isn’t it determined by the font and the text to be output? Here’s an example, with two pieces of text laid out in a Column():

@Composable
@Preview
fun ColumnWithTexts() {
  Column {
    Text(
      text = "Android UI development with Jetpack Compose",
      style = MaterialTheme.typography.headlineMedium,
    )
    Text(
      text = "Hello Compose",
      style = MaterialTheme
        .typography.headlineSmall
   ...

Creating custom layouts

Sometimes, you may want to lay children out one after another in a row and start a new row when the current one has been filled. The CustomLayoutDemo sample app, as shown in the following screenshot, shows you how to do this. It creates 43 randomly colored boxes that vary in width and height:

Figure 4.4 – Sample CustomLayoutDemo app

Figure 4.4 – Sample CustomLayoutDemo app

Let’s start by looking at the composable function that creates colored boxes:

@Composable
fun ColoredBox() {
  Box(
    modifier = Modifier
      .border(
        width = 2.dp,
        color = Color.Black
      )
      .background(randomColor())
      .width((40 * randomInt123()).dp)
      .height((10 * randomInt123()).dp)
 ...

Summary

This chapter explored the predefined layouts of Row(), Column(), and Box(). You learned how to combine them to create beautiful UIs. You were also introduced to ConstraintLayout, which places composables that are relative to others on the screen and flattens the UI element hierarchy.

The second main section explained why the layout system in Jetpack Compose is more performant than the traditional View-based approach. We looked at some of the internals of the Compose runtime, which prepared us for the final main section of this chapter, Creating custom layouts, where you learned how to create a custom layout and thus gain precise control over the rendering of its children.

The next chapter, Chapter 5, Managing State of Your Composable Functions, will deepen your knowledge of state. We will look at advanced use cases and learn more about Jetpack Compose’s reactive state primitives.

Questions

  1. Using Jetpack Compose, it’s perfectly OK to nest layouts. Why is that?
  2. Which building blocks are needed to create a custom Compose layout?
  3. Which parameters may custom layouts want to receive at least?
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Android UI Development with Jetpack Compose - Second Edition
Published in: Nov 2023Publisher: PacktISBN-13: 9781837634255
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 €14.99/month. Cancel anytime

Author (1)

author image
Thomas Künneth

Thomas Künneth is a Google Developer Expert for Android and has been a speaker and panelist at multiple international conferences about Android. Currently, Thomas works as a senior Android developer at Snapp Mobile. He has authored countless articles as well as one of the top-selling German Android books (currently in its sixth edition). He has also frequently contributed to various open source projects.
Read more about Thomas Künneth