1. Welcome
Introduction
As you learned in 1.2 Part A: Your first interactive UI, you can build a user interface (UI) using ConstraintLayout
in the layout editor, which places UI elements in a layout using constraint connections to other elements and to the layout edges. ConstraintLayout
was designed to make it easy to drag UI elements into the layout editor.
ConstraintLayout
is a ViewGroup
, which is a special View
that can contain other View
objects (called children or child views). This practical shows more features of ConstraintLayout
and the layout editor.
This practical also introduces two other ViewGroup
subclasses:
LinearLayout
: A group that aligns childView
elements within it horizontally or vertically.RelativeLayout
: A group of childView
elements in which eachView
element is positioned and aligned relative to otherView
element within theViewGroup
. Positions of the childView
elements are described in relation to each other or to the parentViewGroup
.
What you should already know
You should be able to:
- Create a Hello World app with Android Studio.
- Run an app on the emulator or a device.
- Create a simple layout for an app with
ConstraintLayout
. - Extract and use string resources.
What you'll learn
- How to create a layout variant for horizontal (landscape) orientation.
- How to create a layout variant for tablets and larger displays.
- How to use a baseline constraint to align UI elements with text.
- How to use the pack and align buttons to align elements in the layout.
- How to position views within a
LinearLayout
. - How to position views within a
RelativeLayout
.
What you'll do
- Create a layout variant for a horizontal display orientation.
- Create a layout variant for tablets and larger displays.
- Modify the layout to add constraints to the UI elements.
- Use
ConstraintLayout
baseline constraints to align elements with text. - Use
ConstraintLayout
pack and align buttons to align elements. - Change the layout to use
LinearLayout
. - Position elements in a
LinearLayout
. - Change the layout to use
RelativeLayout
. - Rearrange the views in the main layout to be relative to each other.
2. App overview
The Hello Toast app in a previous lesson uses ConstraintLayout
to arrange the UI elements in the Activity
layout, as shown in the figure below.
To gain more practice with ConstraintLayout
, you will create a variant of this layout for horizontal orientation as shown in the figure below.
You will also learn how to use baseline constraints and some of the alignment features of ConstraintLayout
by creating another layout variant for tablet displays.
You also learn about other ViewGroup
subclasses such as LinearLayout
and RelativeLayout
, and change the Hello Toast app layout to use them.
3. Task 1: Create layout variants
In the previous lesson, the coding challenge required changing the layout of the Hello Toast app so that it would fit properly in a horizontal or vertical orientation. In this task you will learn an easier way to create variants of your layout for horizontal (also known as landscape) and vertical (also known as portrait) orientations for phones, and for larger displays such as tablets.
In this task you will use some of the buttons in the top two toolbars of the layout editor. The top toolbar lets you configure the appearance of the layout preview in the layout editor:
In the figure above:
- Select Design Surface: Select Design to display a color preview of your layout, or Blueprint to show only outlines for each UI element. To see both panes side by side, select Design + Blueprint.
- Orientation in Editor: Select Portrait or Landscape to show the preview in a vertical or horizontal orientation. This is useful for previewing the layout without having to run the app on an emulator or device. To create alternative layouts, select Create Landscape Variation or other variations.
- Device in Editor: Select the device type (phone/tablet, Android TV, or Android Wear).
- API Version in Editor: Select the version of Android to use to show the preview.
- Theme in Editor: Select a theme (such as AppTheme) to apply to the preview.
- Locale in Editor: Select the language and locale for the preview. This list displays only the languages available in the string resources (see the lesson on localization for details on how to add languages). You can also choose Preview as Right To Left to view the layout as if an RTL language had been chosen.
The second toolbar lets you configure the appearance of UI elements in a ConstraintLayout
, and to zoom and pan the preview:
In the figure above:
- Show: Choose Show Constraints and Show Margins to show them in the preview, or to stop showing them.
- Autoconnect: Enable or disable Autoconnect. With Autoconnect enabled, you can drag any element (such as a
Button
) to any part of a layout to generate constraints against the parent layout. - Clear All Constraints: Clear all constraints in the entire layout.
- Infer Constraints: Create constraints by inference.
- Default Margins: Set the default margins.
- Pack: Pack or expand the selected elements.
- Align: Align the selected elements.
- Guidelines: Add vertical or horizontal guidelines.
- Zoom/pan controls: Zoom in or out.
Tip: To learn more about using the layout editor, see Build a UI with Layout Editor. To learn more about how to build a layout with ConstraintLayout, see Build a Responsive UI with ConstraintLayout.
1.1 Preview the layout in a horizontal orientation
To preview the Hello Toast app layout with a horizontal orientation, follow these steps:
- Open the Hello Toast app from the previous lesson.
Note: If you downloaded the solution code for HelloToast, you need to delete the finished landscape and extra-large layouts that you will create in this task. Switch from Project > Android to Project > Project Files in the Project pane, expand app > app > src/main > res, select both the layout-land folder and the layout-xlarge folder, and choose Edit > Delete. Then switch the Project pane back to Project > Android.
- Open the activity_main.xml layout file. Click the Design tab if it is not already selected.
- Click the Orientation in Editor button
in the top toolbar.
- Select Switch to Landscape in the dropdown menu. The layout appears in horizontal orientation as shown below. To return to vertical orientation, select Switch to Portrait.
1.2 Create a layout variant for horizontal orientation
The visual difference between vertical and horizontal orientations for this layout is that the digit (0
) in the show_count
TextView
element is too low for the horizontal orientation—too close to the Count button. Depending on which device or emulator you use, the TextView
element may appear too large or not centered because the text size is fixed to 160sp.
To fix this for horizontal orientations while leaving vertical orientations alone, you can create variant of the Hello Toast app layout that is different for a horizontal orientation. Follow these steps:
- Click the Orientation in Editor button
in the top toolbar.
- Choose Create Landscape Variation.
A new editor window opens with the land/activity_main.xml tab showing the layout for the landscape (horizontal) orientation. You can change this layout, which is specifically for horizontal orientation, without changing the original portrait (vertical) orientation.
- In the Project > Android pane, look inside the res > layout directory, and you will see that Android Studio automatically created the variant for you, called
activity_main.xml (land)
.
1.3 Preview the layout for different devices
You can preview the layout for different devices without having to run the app on the device or emulator. Follow these steps:
- The land/activity_main.xml tab should still be open in the layout editor; if not, double-click the activity_main.xml (land) file in the layout directory.
- Click the Device in Editor button
in the top toolbar.
- Choose a different device in the dropdown menu. For example, choose Nexus 4, Nexus 5, and then Pixel to see differences in the previews. These differences are due to the fixed text size for the
TextView
.
1.4 Change the layout for horizontal orientation
You can use the Attributes pane in the Design tab to set or change attributes, but it can sometimes be quicker to use the Text tab to edit the XML code directly. The Text tab shows the XML code and provides a Preview tab on the right side of the window to show the layout preview, as shown in the figure below.
The figure above shows the following:
- The Preview tab, which you use to show the preview pane
- The preview pane
- The XML code
To change the layout, follow these steps:
- The land/activity_main.xml tab should still be open in the layout editor; if not, double-click the activity_main.xml (land) file in the layout directory.
- Click the Text tab and the Preview tab (if not already selected).
- Find the
TextView
element in the XML code. - Change the
android:textSize="160sp"
attribute toandroid:textSize="120sp"
. The layout preview shows the result:
- Choose different devices in the Device in Editor dropdown menu to see how the layout looks on different devices in horizontal orientation.
In the editor pane, the land/activity_main.xml tab shows the layout for horizontal orientation. The activity_main.xml tab shows the unchanged layout for vertical orientation. You can switch back and forth by clicking the tabs.
- Run the app on an emulator or device, and switch the orientation from vertical to horizontal to see both layouts.
1.5 Create a layout variant for tablets
As you learned previously, you can preview the layout for different devices by clicking the Device in Editor button in the top toolbar. If you pick a device such as Nexus 10 (a tablet) from the menu, you can see that the layout is not ideal for a tablet screen—the text of each
Button
is too small, and the arrangement of the Button
elements at the top and bottom is not ideal for a large-screen tablet.
To fix this for tablets while leaving the phone-size horizontal and vertical orientations alone, you can create variant of the layout that is completely different for tablets. Follow these steps:
- Click the Design tab (if not already selected) to show the design and blueprint panes.
- Click the Orientation in Editor button
in the top toolbar.
- Choose Create layout x-large Variation.
A new editor window opens with the xlarge/activity_main.xml tab showing the layout for a tablet-sized device. The editor also picks a tablet device, such as the Nexus 9 or Nexus 10, for the preview. You can change this layout, which is specifically for tablets, without changing the other layouts.
1.6 Change the layout variant for tablets
You can use the Attributes pane in the Design tab to change attributes for this layout.
- Turn off the Autoconnect tool in the toolbar. For this step, ensure that the tool is disabled:
- Clear all constraints in the layout by clicking the Clear All Constraints
button in the toolbar.
With constraints removed, you can move and resize the elements on the layout freely.
- The layout editor offers resizing handles on all four corners of an element to resize it. In the Component Tree, select the
TextView
calledshow_count
. To get theTextView
out of the way so that you can freely drag theButton
elements, drag a corner of it to resize it, as shown in the animated figure below.
Resizing an element hardcodes the width and height dimensions. Avoid hardcoding the size dimensions for most elements, because you can't predict how hardcoded dimensions will look on screens of different sizes and densities. You are doing this now just to move the element out of the way, and you will change the dimensions in another step.
- Select the
button_toast
Button
in the Component Tree, click the Attributes tab to open the Attributes pane, and change thetextSize
to 60sp (#1 in the figure below) and thelayout_width
to wrap_content (#2 in the figure below).
As shown on the right side of the figure above (2), you can click the view inspector's width control, which appears in two segments on the left and right sides of the square, until it shows Wrap Content
. As an alternative, you can select wrap_content from the layout_width
menu.
You use wrap_content
so that if the Button
text is localized into a different language, the Button
will appear wider or thinner to accommodate the word in the different language.
- Select the
button_count
Button
in the Component Tree, change thetextSize
to 60sp and thelayout_width
to wrap_content, and drag theButton
above theTextView
to an empty space in the layout.
1.7 Use a baseline constraint
You can align one UI element that contains text, such as a TextView
or Button
, with another UI element that contains text. A baseline constraint lets you constrain the elements so that the text baselines match.
- Constrain the
button_toast
Button
to the top and left side of the layout, drag thebutton_count
Button
to a space near thebutton_toast
Button
, and constrain the left side of thebutton_count
Button
to the right side of thebutton_toast
Button
, as shown in the animated figure:
- Using a baseline constraint, you can constrain the
button_count
Button
so that its text baseline matches the text baseline of thebutton_toast
Button
. Select thebutton_count
element, and then hover your pointer over the element until the baseline constraint buttonappears underneath the element.
- Click the baseline constraint button. The baseline handle appears, blinking in green as shown in the animated figure. Click and drag a baseline constraint line to the baseline of the
button_toast
element.
1.8 Expand the buttons horizontally
The pack button in the toolbar provides options for packing or expanding selected UI elements. You can use it to equally arrange the
Button
elements horizontally across the layout.
- Select the
button_count
Button
in the Component Tree, and Shift-select thebutton_toast
Button
so that both are selected. - Click the pack button
in the toolbar, and choose Expand Horizontally as shown in the figure below.
The Button
elements expand horizontally to fill the layout as shown below.
- To finish the layout, constraint the
show_count
TextView
to the bottom of thebutton_toast
Button
and to the sides and bottom of the layout, as shown in the animated figure below.
- The final steps are to change the
show_count
TextView
layout_width
andlayout_height
to Match Constraints and thetextSize
to 200sp. The final layout looks like the figure below.
- Click the Orientation in Editor button
in the top toolbar and choose Switch to Landscape. The tablet layout appears in horizontal orientation as shown below. (You can choose Switch to Portrait to return to vertical orientation.).
- Run the app on different emulators, and change the orientation after running the app, to see how it looks on different types of devices. You have successfully created an app that can run with a proper UI on phones and tablets that have different screen sizes and densities.
Tip: For an in-depth tutorial on using ConstraintLayout
, see Using ConstraintLayout to design your views.
Task 1 solution code
Android Studio project: HelloToast
4. Coding challenge 1
Challenge: To accommodate horizontal (landscape) orientation for a tablet, you can center the Button elements in activity_main.xml (xlarge)
so that they appear as shown in the figure below.
Hint: Select the elements, click the align button in the toolbar, and choose Center Horizontally.
Challenge 1 solution code
Android Studio project: HelloToastChallenge2
5. Task 2: Change the layout to LinearLayout
LinearLayout
is a ViewGroup
that arranges its collection of views in a horizontal or vertical row. A LinearLayout
is one of the most common layouts because it is simple and fast. It is often used within another view group to arrange UI elements horizontally or vertically.
A LinearLayout
is required to have these attributes:
layout_width
layout_height
orientation
The layout_width
and layout_height
can take one of these values:
match_parent
: Expands the view to fill its parent by width or height. When theLinearLayout
is the root view, it expands to the size of the screen (the parent view).wrap_content
: Shrinks the view dimensions so the view is just big enough to enclose its content. If there is no content, the view becomes invisible.- Fixed number of dp ( density-independent pixels): Specify a fixed size, adjusted for the screen density of the device. For example,
16dp
means 16 density-independent pixels.
The orientation
can be:
horizontal
: Views are arranged from left to right.vertical
: Views are arranged from top to bottom.
In this task you will change the ConstraintLayout
root view group for the Hello Toast app to LinearLayout
so that you can gain practice in using LinearLayout
.
2.1 Change the root view group to LinearLayout
- Open the Hello Toast app from the previous task.
- Open the
activity_main.xml
layout file (if it is not already open), and click the Text tab at the bottom of the editing pane to see the XML code. At the very top of the XML code is the following tag line:
<android.support.constraint.ConstraintLayout xmlns:android="http:...
- Change the
<android.support.constraint.ConstraintLayout
tag to <LinearLayout so that the code looks like this:
<LinearLayout xmlns:android="http:...
- Make sure the closing tag at the end of the code has changed to
</LinearLayout>
(Android Studio automatically changes the closing tag if you change the opening tag). If it hasn't changed automatically, change it manually. - Under the
<LinearLayout
tag line, add the following attribute after theandroid:layout_height
attribute:
android:orientation="vertical"
After making these changes, some of the XML attributes for other elements are underlined in red because they are used with ConstraintLayout
and are not relevant for LinearLayout
.
2.2 Change element attributes for the LinearLayout
Follow these steps to change UI element attributes so that they work with LinearLayout
:
- Open the Hello Toast app from the previous task.
- Open the
activity_main.xml
layout file (if it is not already open), and click the Text tab. - Find the
button_toast
Button
element, and change the following attribute:
Original | Change to |
|
|
- Delete the following attributes from the
button_toast
element:
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
- Find the
button_count
Button
element, and change the following attribute:
Original | Change to |
|
|
- Delete the following attributes from the
button_count
element:
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
- Find the
show_count
TextView
element, and change the following attributes:
Original | Change to |
|
|
|
|
- Delete the following attributes from the
show_count
element:
app:layout_constraintBottom_toTopOf="@+id/button_count"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button_toast"
- Click the Preview tab on the right side of the Android Studio window (if it is not already selected) to see a preview of the layout thus far:
2.3 Change the positions of elements in the LinearLayout
LinearLayout
arranges its elements in a horizontal or vertical row. You have already added the android:orientation="vertical"
attribute for the LinearLayout, so the elements are stacked on top of each other vertically as shown in the previous figure.
To change their positions so that the Count button is on the bottom, follow these steps:
- Open the Hello Toast app from the previous task.
- Open the
activity_main.xml
layout file (if it is not already open), and click the Text tab. - Select the
button_count
Button
and all of its attributes, from the<Button
tag up to and including the closing/>
tag, and choose Edit > Cut. - Click after the closing
/>
tag of theTextView
element but before the closing</LinearLayout>
tag, and choose Edit > Paste. - (Optional) To fix any indents or spacing issues for cosmetic purposes, choose Code > Reformat Code to reformat the XML code with proper spacing and indents.
The XML code for the UI elements now looks like the following:
<Button
android:id="@+id/button_toast"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:background="@color/colorPrimary"
android:onClick="showToast"
android:text="@string/button_label_toast"
android:textColor="@android:color/white" />
<TextView
android:id="@+id/show_count"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:background="#FFFF00"
android:gravity="center_vertical"
android:text="@string/count_initial_value"
android:textAlignment="center"
android:textColor="@color/colorPrimary"
android:textSize="160sp"
android:textStyle="bold" />
<Button
android:id="@+id/button_count"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:background="@color/colorPrimary"
android:onClick="countUp"
android:text="@string/button_label_count"
android:textColor="@android:color/white" />
By moving the button_count
Button
below the TextView
, the layout is now close to what you had before, with the Count button on the bottom. The preview of the layout now looks like the following:
2.4 Add weight to the TextView element
Specifying gravity
and weight
attributes gives you additional control over arranging views and content in a LinearLayout
.
The android:gravity
attribute specifies the alignment of the content of a View
within the View
itself. In the previous lesson you set this attribute for the show_count
TextView
in order to center the content (the digit 0) in the middle of the TextView
:
android:gravity="center_vertical"
The android:layout_weight
attribute indicates how much of the extra space in the LinearLayout
will be allocated to the View
. If only one View
has this attribute, it gets all the extra screen space. For multiple View
elements, the space is prorated. For example, if the Button
elements each have a weight of 1 and the TextView
2, totaling 4, the Button
elements get ¼ of the space each, and the TextView
half.
On different devices, the layout may show the show_count
TextView
element as filling part or most of the space between the Toast and Count buttons. In order to expand the TextView
to fill the available space no matter which device is used, specify the android:gravity
attribute for the TextView
. Follow these steps:
- Open the Hello Toast app from the previous task.
- Open the
activity_main.xml
layout file (if it is not already open), and click the Text tab. - Find the
show_count
TextView
element, and add the following attribute:
android:layout_weight="1"
The preview now looks like the following figure.
The show_count
TextView
element takes up all the space between the buttons. You can preview the layout for different devices, as you did in a previous task by clicking the Device in Editor button in the top toolbar of the preview pane, and choosing a different device. No matter which device you choose for the preview, the
show_count
TextView
element should take up all the space between the buttons.
Task 2 solution code
The XML code in activity_main.xml
:
<LinearLayout 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"
android:orientation="vertical"
tools:context="com.example.android.hellotoast.MainActivity">
<Button
android:id="@+id/button_toast"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:background="@color/colorPrimary"
android:onClick="showToast"
android:text="@string/button_label_toast"
android:textColor="@android:color/white" />
<TextView
android:id="@+id/show_count"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:background="#FFFF00"
android:text="@string/count_initial_value"
android:textAlignment="center"
android:textColor="@color/colorPrimary"
android:textSize="160sp"
android:textStyle="bold"
android:layout_weight="1"/>
<Button
android:id="@+id/button_count"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:background="@color/colorPrimary"
android:onClick="countUp"
android:text="@string/button_label_count"
android:textColor="@android:color/white" />
</LinearLayout>
6. Task 3: Change the layout to RelativeLayout
A RelativeLayout
is a view grouping in which each view is positioned and aligned relative to other views within the group. In this task you will learn how to build a layout with RelativeLayout
.
3.1 Change LinearLayout to RelativeLayout
An easy way to change the LinearLayout
to a RelativeLayout
is to add XML attributes in the Text tab.
- Open the activity_main.xml layout file, and click the Text tab at the bottom of the editing pane to see the XML code.
- Change the
<LinearLayout
at the top to <RelativeLayout so that the statement looks like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- Scroll down to make sure that the ending tag
</LinearLayout>
has also changed to</RelativeLayout>
; if it hasn't, change it manually.
3.2 Rearrange views in a RelativeLayout
An easy way to rearrange and position views in a RelativeLayout is to add XML attributes in the Text tab.
- Click the Preview tab at the side of the editor (if it is not already selected) to see the layout preview, which now looks like the figure below.
With the change to RelativeLayout
, the layout editor also changed some of the view attributes. For example:
- The Count
Button
(button_count
) overlays the ToastButton
, which is why you can't see the ToastButton
(button_toast
). - The top part of the
TextView
(show_count
) overlays theButton
elements.
- Add the
android:layout_below
attribute to thebutton_count
Button
to position theButton
directly below theshow_count
TextView
. This attribute is one of several attributes for positioning views within aRelativeLayout
—you place views in relation to other views.
android:layout_below="@+id/show_count"
- Add the
android:layout_centerHorizontal
attribute to the sameButton
to center the view horizontally within its parent, which in this case is theRelativeLayout
view group.
android:layout_centerHorizontal="true"
The full XML code for the button_count
Button
is as follows:
<Button
android:id="@+id/button_count"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:background="@color/colorPrimary"
android:onClick="countUp"
android:text="@string/button_label_count"
android:textColor="@android:color/white"
android:layout_below="@+id/show_count"
android:layout_centerHorizontal="true"/>
- Add the following attributes to the
show_count
TextView
:
android:layout_below="@+id/button_toast"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
The android:layout_alignParentLeft
aligns the view to the left side of the RelativeLayout
parent view group. While this attribute by itself is enough to align the view to the left side, you may want the view to align to the right side if the app is running on a device that is using a right-to-left language. Thus, the android:layout_alignParentStart
attribute makes the "start" edge of this view match the start edge of the parent. The start is the left edge of the screen if the preference is left-to-right, or it is the right edge of the screen if the preference is right-to-left.
- Delete the
android:layout_weight="1"
attribute from theshow_count
TextView
, which is not relevant for aRelativeLayout
. The layout preview now looks like the following figure:
Tip: RelativeLayout
makes it relatively easy to quickly place UI elements in a layout. To learn more about how to position views in a RelativeLayout
, see " Positioning Views" in the "Relative Layout" topic of the API Guide.
Task 3 solution code
The XML code in activity_main.xml
:
<RelativeLayout 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"
android:orientation="vertical"
tools:context="com.example.android.hellotoast.MainActivity">
<Button
android:id="@+id/button_toast"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:background="@color/colorPrimary"
android:onClick="showToast"
android:text="@string/button_label_toast"
android:textColor="@android:color/white" />
<TextView
android:id="@+id/show_count"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:background="#FFFF00"
android:text="@string/count_initial_value"
android:textAlignment="center"
android:textColor="@color/colorPrimary"
android:textSize="160sp"
android:textStyle="bold"
android:layout_below="@+id/button_toast"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:id="@+id/button_count"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:background="@color/colorPrimary"
android:onClick="countUp"
android:text="@string/button_label_count"
android:textColor="@android:color/white"
android:layout_below="@+id/show_count"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
7. Summary
Using the layout editor to preview and create variants:
- To preview the app layout with a horizontal orientation in the layout editor, click the Orientation in Editor button
in the top toolbar and choose Switch to Landscape. Choose Switch to Portrait to return to vertical orientation.
- To create variant of the layout that is different for a horizontal orientation, click the Orientation in Editor button and choose Create Landscape Variation. A new editor window opens with the land/activity_main.xml tab showing the layout for the landscape (horizontal) orientation.
- To preview the layout for different devices without having to run the app on the device or emulator, click the Device in Editor button
in the top toolbar, and choose a device.
- To create variant of the layout that is different for a tablet (larger screen), click the Orientation in Editor button and choose Create layout x-large Variation. A new editor window opens with the xlarge/activity_main.xml tab showing the layout for a tablet-sized device.
Using ConstraintLayout
:
- To clear all constraints in a layout with the
ConstraintLayout
root, click the Clear All Constraintsbutton in the toolbar.
- You can align one UI element that contains text, such as a
TextView
orButton
, with another UI element that contains text. A baseline constraint lets you constrain the elements so that the text baselines match. - To create a baseline constraint, hover your pointer over the UI element until the baseline constraint button
appears underneath the element.
- The pack button
in the toolbar provides options for packing or expanding selected UI elements. You can use it to equally arrange the
Button
elements horizontally across the layout.
Using LinearLayout
:
LinearLayout
is aViewGroup
that arranges its collection of views in a horizontal or vertical row.- A
LinearLayout
is required to have thelayout_width
,layout_height
, andorientation
attributes. match_parent
forlayout_width
orlayout_height
: Expands theView
to fill its parent by width or height. When theLinearLayout
is the rootView
, it expands to the size of the screen (the parentView
).Wrap_content
forlayout_width
orlayout_height
: Shrinks the dimensions so theView
is just big enough to enclose its content. If there is no content, theView
becomes invisible.- Fixed number of dp ( density-independent pixels) for
layout_width
orlayout_height
: Specify a fixed size, adjusted for the screen density of the device. For example,16dp
means 16 density-independent pixels. - The
orientation
for aLinearLayout
can behorizontal
to arrange elements from left to right, orvertical
to arrange elements from top to bottom. - Specifying
gravity
andweight
attributes gives you additional control over arranging views and content in aLinearLayout
. - The
android:gravity
attribute specifies the alignment of the content of aView
within theView
itself. - The
android:layout_weight
attribute indicates how much of the extra space in theLinearLayout
will be allocated to theView
. If only oneView
has this attribute, it gets all the extra screen space. For multipleView
elements, the space is prorated. For example, if twoButton
elements each have a weight of 1 and aTextView
2, totaling 4, theButton
elements get ¼ of the space each, and theTextView
half.
Using RelativeLayout
:
- A
RelativeLayout
is aViewGroup
in which each view is positioned and aligned relative to other views within the group. - Use
android:layout_alignParentTop
to align theView
to the top of the parent. - Use
android:layout_alignParentLeft
to align theView
to the left side of the parent. - Use
android:layout_alignParentStart
to make the start edge of theView
match the start edge of the parent. This attribute is useful if you want your app to work on devices that use different language or locale preferences. The start is the left edge of the screen if the preference is left-to-right, or it is the right edge of the screen if the preference is right-to-left.
8. Related concepts
The related concept documentation is in 1.2: Layouts and resources for the UI.
9. Learn more
Android Studio documentation:
Android developer documentation:
- Layouts
- Build a UI with Layout Editor
- Build a Responsive UI with ConstraintLayout
- Layouts
LinearLayout
RelativeLayout
View
Button
TextView
- Supporting different pixel densities
Other:
10. Homework
This section lists possible homework assignments for students who are working through this codelab as part of a course led by an instructor. It's up to the instructor to do the following:
- Assign homework if required.
- Communicate to students how to submit homework assignments.
- Grade the homework assignments.
Instructors can use these suggestions as little or as much as they want, and should feel free to assign any other homework they feel is appropriate.
If you're working through this codelab on your own, feel free to use these homework assignments to test your knowledge.
Change an app
Open the HelloToast app.
- Change the name of the project to HelloConstraint, and refactor the project to
Hello Constraint
. (For instructions on how to copy and refactor a project, see Appendix: Utilities.) - Modify the
activity_main.xml
layout to align the Toast and CountButton
elements along the left side of theshow_count
TextView
that shows "0". Refer to the figures below for the layout. - Include a third
Button
called Zero that appears between the Toast and CountButton
elements. - Distribute the
Button
elements vertically between the top and bottom of theshow_count
TextView
. - Set the Zero
Button
to initially have a gray background. - Make sure that you include the Zero
Button
for the landscape orientation inactivity_main.xml (land)
, and also for a tablet-sized screen inactivity_main (xlarge)
. - Make the Zero
Button
change the value in theshow_count
TextView
to 0. - Update the click handler for the Count
Button
so that it changes its own background color, depending on whether the new count is odd or even.
Hint: Don't use findViewById
to find the Count Button
. Is there something else you can use?
Feel free to to use constants in the Color
class for the two different background colors.
- Update the click handler for the Count
Button
to set the background color for the ZeroButton
to something other than gray to show it is now active. Hint: You can usefindViewById
in this case. - Update the click handler for the Zero
Button
to reset the color to gray, so that it is gray when the count is zero.
Answer these questions
Question 1
Which two layout constraint attributes on the Zero Button
position it vertically equal distance between the other two Button
elements? (Pick 2 answers.)
app:layout_constraintBottom_toTopOf="@+id/button_count"
android:layout_marginBottom="8dp"
android:layout_marginStart="16dp"
app:layout_constraintTop_toBottomOf="@+id/button_toast"
android:layout_marginTop="8dp"
Question 2
Which layout constraint attribute on the Zero Button
positions it horizontally in alignment with the other two Button
elements?
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintBottom_toTopOf="@+id/button_count"
android:layout_marginBottom="8dp"
app:layout_constraintTop_toBottomOf="@+id/button_toast"
Question 3
What is the correct signature for a method used with the android:onClick
XML attribute?
public void callMethod()
public void callMethod(View view)
private void callMethod(View view)
public boolean callMethod(View view)
Question 4
The click handler for the Count Button
starts with the following method signature:
public void countUp(View view)
Which of the following techniques is more efficient to use within this handler to change the Button
element's background color? Choose one:
- Use
findViewById
to find the CountButton
. Assign the result to aView
variable, and then usesetBackgroundColor()
. - Use the
view
parameter that is passed to the click handler withsetBackgroundColor()
:view.setBackgroundColor()
Submit your app for grading
Guidance for graders
Check that the app has the following features:
- It displays the Zero button.
- The Zero button is between the Toast and Count buttons.
- The app includes an implementation of
activity_main.xml
,activity_main.xml (land)
, andactivity_main.xml (xlarge)
. - The app includes an implementation of the click handler method for the Zero button to reset the count to 0. The method must show the zero count in the
show_count
TextView
. The click handler must also reset the Zero button's own background color to gray. - The click handler method for the Count button has been updated to change its own background color depending on whether the new count is odd or even. This method must use the
view
parameter to access the button. This method must also change the background of the Zero button to a color other than gray.
11. Next codelab
To find the next practical codelab in the Android Developer Fundamentals (V2) course, see Codelabs for Android Developer Fundamentals (V2).
For an overview of the course, including links to the concept chapters, apps, and slides, see Android Developer Fundamentals (Version 2).