Introducing ConstraintLayout
The starter app that we examined in the opening chapters had a layout like this:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
This wraps a single TextView
in a ConstraintLayout
. For the purposes of what this “hello, world!” app does, the ConstraintLayout
is pointless — we saw activities using just a TextView
in the chapter on widgets.
However, more often than not, you will have more than one widget in your layout resources. When you do, you will always have some sort of container, and frequently that container will be a ConstraintLayout
.
In this chapter, we will review what containers are and why we use them, examine some basic scenarios for using ConstraintLayout
, and look at another widget: EditText
.
The Role of Containers
Some apps have screens that contain just one widget.
Not many, though.
Most of the time, our user interface is more complicated than that… even if it does not seem that complicated when you look at it:
Here we have:
- Three checkboxes
- Three labels adjacent to those checkboxes
- Some sort of title (“ToDo”)
- A strange little “…” icon in the upper right
- A yellow background behind the title and icon
This takes more than one XML element to represent in a layout resource. In fact, this takes more than one layout resource. This app is a “to-do list” sort of app, and it can handle an arbitrary number of to-do items. So while this screenshot shows three rows of checkboxes-and-labels, really the user could have 0 to N of them.
As we covered previously, containers extend from ViewGroup
, and the job of a ViewGroup
is to organize some number of children and display them on the screen. ViewGroup
itself extends from View
, so the children of a ViewGroup
can be a mix of View
and ViewGroup
objects.
So, in this screenshot, we clearly have at least one ViewGroup
that is organizing all of those widgets and displaying them.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.