Home Android & Kotlin Books Android Apprentice

Layouts Written by Darryl Bayliss

If bricks and mortar are the foundation of a sturdy building, then Layouts are the Android equivalent of a sturdy app. Layouts are incredibly flexible. They let you define how to present your app’s user interface on the device. You can create Layouts in one of two ways:

  1. Using an XML file to declare the user interface ahead of time.
  2. Writing Kotlin code to create the layout at runtime programmatically.

In this book, you’ll define your Layouts ahead of time using XML — that’s because Android Studio has a powerful Layout editor that covers 90% of the cases you’ll ever need when creating a user interface.

Getting started

Before diving into the wonderful world of Layouts, take a few moments to think about what makes up an app. Most often, an app is a self-contained program allowing users to perform one or more tasks.

When you build an app, you want your users to accomplish those tasks quickly and intuitively, which is why a well-thought-out user interface is so important.

The app you’ll build in this section, Timefighter, is no different. It’s minimal in its design, so usability isn’t an issue.

Your first task is to set up the user interface, which has two TextViews and one Button.

Locate the projects folder for this chapter and open the Timefighter app inside the starter folder. The first time you open the project, Android Studio will take a few minutes to set up the environment and update its dependencies. After that, you’re ready to rock and roll!

These are not the SDKs you’re looking for

When you open the project, you might get the following error in the Build tab:

If you followed along in the previous chapter and installed a fresh version of Android Studio, you may not see this error. However, if you’re already running Android Studio, it’s possible that you don’t have the version of the Android SDK that was used to create this project.

Do not fret young padawan learner; Android Studio will always do its best to help resolve these sorts of issues for you. On the right, Android Studio provides you with a convenient link, that when clicked, will install the required version of the Android SDK and rebuild your project.

After this error disappears, you’ll see the following in the Build tab:

Excellent! It’s time to get comfy with everything Android Studio has to offer.

The layout editor

In the project structure sidebar on the left of Android Studio, expand app, res, and finally layout. Then, double-click activity_main.xml and you’ll see a screen that looks like this:

Editing activity_main.xml using the layout editor
Editing activity_main.xml using the layout editor

Behold the layout editor!

The layout editor should open up in split mode, with the middle of Android Studio shows a few different screens. If not, click the Split button in the top right of the layout editor.

The first screen, located on the right next to what looks like a blueprint, is the preview area. This is where you’ll begin to build the user interface.

On the top right of the layout editor, you’ll find three buttons: Code, Split, and Design.

Switch between code view, split view and design view
Switch between code view, split view and design view

Click Code, the button on the left, and Android Studio switches windows:

Editing activity_main.xml using the XML Editor
Editing activity_main.xml using the XML Editor

In the middle section of Android Studio, you’ll see the Text editor. This shows the XML representation of the app’s first screen.

In the top right. Click the Design button on the far right. Android Studio changes again to show only the screen in a visual format.

Editing activity_main.xml using the design editor
Editing activity_main.xml using the design editor

You’ll start by adding a TextView to the user interface. In the top-left of the middle section of Android Studio, you’ll see the Palette:

Palette of interface components
Palette of interface components

This contains all of the built-in user interface components that you can use to build the screens for your Android app. What’s more useful is that you can drag and drop from this palette directly into the Preview screen to add a component.

Open the Palette and select Text. The palette changes and shows text-related components.

Next, drag a TextView from the Palette — this is for your score label — and drop it in the top-left of the Preview screen.

Component tree view

Before moving on, it’s worth knowing that although dragging and dropping components into the Preview area is relatively easy to do, it can be tricky to get things to show up in the right spot, especially when you’re dealing with projects that have many views.

As an alternative, you can drag components from the Palette directly into a Component Tree, dropping it underneath the desired parent component.

Keep that little feather in your cap as you progress through this book, because you may find it easier to drop components in this way, and then deal with positioning them later.

Positioning your views

At this point, you have the start of your app, with your TextView sitting in the top left-hand corner. There is an issue here though, the app doesn’t know where to place the TextView — and you can prove it!

In the visual editor, drag the newly placed TextView somewhere in the middle of the screen, like so:

Layout as seen in the design editor
Layout as seen in the design editor

Click Run ‘app’ along the top of Android Studio to run your app on a device.

Layout as seen on device
Layout as seen on device

Hey, that’s not where you placed the TextView! But don’t worry; in the next section, you’ll ensure the TextView stays put.

Adding rules to your views

There are millions of Android devices in the world, in all shapes and sizes. To ensure your app looks great on all of those different screens, you need to edit the layout and give the TextView rules on where it should be positioned on the screen.

The Blueprint screen to the right of the preview gives you a visual representation of the rules that exist within your Layout. You’ll use this tool to create new rules for your TextView.

In the Preview screen, click and drag the TextView to the top-left corner of the screen. Now, hover your mouse over the left side of the newly placed TextView in the Blueprint screen. A circle with a white outline appears:

Click and drag toward the left edge of the Blueprint screen, and you’ll see the TextView move slightly to the left. At this point, release the mouse button.

Congratulations, you just created your first layout rule!

Next, you need to create the top layout rule. Move your mouse to the top of the TextView until the outlined circle appears, and drag to the top edge of the screen until the TextView moves up slightly. Release the mouse button again to create the second layout rule.

To see what’s happening, select the TextView and look for a panel on the right side of Android Studio in the Attributes window. Look at the top of the Properties window, and you’ll see a square with chevrons inside:

Layout rule for your TextView
Layout rule for your TextView

If you look closely, you’ll see two solid lines running from the left and the top of the rectangle, pushing against two gray rectangles with a number 0 floating beside them. These are the rules, or constraints, you just created that hold your TextView against the edges of the screen, and they instruct the TextView how to position itself relative to the screen’s edge.

If you want to position this TextView with greater control, you can adjust the margins of the constraint by clicking the number beside the constraint line and selecting one of the preset numbers in the drop-down or entering your own.

That TextView is looking squashed against the edge of the screen, so you’ll add some margins to it now.

Adjust both the left constraint margin and the top constraint margin by entering 8 into the margin dropdowns:

Adjust the margins for your TextView
Adjust the margins for your TextView

Your TextView will also look more evenly spaced in the visual editor:

In the final section, you’ll finish off the screen!

Finishing the screen

Go back to the Palette window and drag another TextView into the Preview window, this time putting it in the top-right corner of the screen to serve as your time remaining label.

In the Blueprint window, select the new TextView and create a new constraint against the right side of the screen.

Then, create a new constraint for the top of the TextView against the top of the screen. Also make sure your new constraints have a margin of 8, to add spacing between the TextView and the edge of the screen.

Your layout will look like this:

That takes care of the two TextViews. All that’s left is the Tap Me! button.

First, remove the TextView floating in the middle of the screen. Select the Hello User! TextView and press the delete key — the TextView disappears.

With the TextView removed, you can add the button.

In the Palette window, click the Common tab. When you see the Button in the Palette, click and drag it to the center of the screen. You may even see some helpful dotted guidelines to help position your Button right in the center of the screen.

Now, you need to create constraints for the Button, just like you did for the TextViews. This Button needs to stay in the center of the screen, so you need four constraints, one for each side of the button.

In the Blueprint screen, hover over each side of the Button and pull the connector toward its respective edge of the screen. The Button will move around quite a bit as you do this but don’t panic, it’s just trying to respect the constraints as you add them.

Once the button has all its constraints, your layout will look like this:

Finally, click Run ‘app’ from the top menu in Android Studio. Your emulator or device loads the latest changes to your app, and all of your hard work is rewarded with an app that contains two correctly placed TextViews and one Button.

Key Points

Setting up your first Layout may take time. It’s worth understanding though, as it’s a process every Android developer goes through when creating screens for their apps. To recap, you learned:

  • How to view a layout by opening the .xml file.

  • What the Code, Split, and Design screens are in the layout editor, and what their uses are.

  • What the palette and component tree in the visual editor are for.

  • How to position textviews and buttons onto the screen.

  • How to setup constraints for your textviews and button, then setup margins for each constraint.

Where to go from here?

Although you learned a lot, you only used a fraction of the power that Constraints offer. There’s a dedicated component for Constraints — ConstraintLayout — that provides all of this functionality.

Other Layouts provide other structures your Views can leverage, such as LinearLayout and FrameLayout among others. It’s recommended to use a ConstraintLayout where ever possible. However, there are times where it might be awkward or not practical.

This book uses ConstraintLayout as its go-to Layout of choice. If you want to learn more about it, review the documentation on ConstraintLayout on the Android Developer site: https://developer.android.com/training/constraint-layout/index.html.

Pat yourself on the back for making it this far! You’ve taken your first step into the world of Android development.

If you had any problems following along with the starter app, review the completed solution in the final folder for this chapter’s materials.

In the next chapter, you’ll attach some logic to your Button and make those TextViews display something more interesting than the words “TextView”. You’ll also get your first taste of writing code. See you there!

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.

Have feedback to share about the online reading experience? If you have feedback about the UI, UX, highlighting, or other features of our online readers, you can send them to the design team with the form below:

© 2021 Razeware LLC