Android fundamentals 01.2 Part A: Your first interactive UI

1. Welcome

Introduction

The user interface (UI) that appears on a screen of an Android device consists of a hierarchy of objects called views — every element of the screen is a View. The View class represents the basic building block for all UI components, and the base class for classes that provide interactive UI components such as buttons, checkboxes, and text entry fields. Commonly used View subclasses described over several lessons include:

The Java code that displays and drives the UI is contained in a class that extends Activity. An Activity is usually associated with a layout of UI views defined as an XML (eXtended Markup Language) file. This XML file is usually named after its Activity and defines the layout of View elements on the screen.

For example, the MainActivity code in the Hello World app displays a layout defined in the activity_main.xml layout file, which includes a TextView with the text "Hello World".

In more complex apps, an Activity might implement actions to respond to user taps, draw graphical content, or request data from a database or the internet. You learn more about the Activity class in another lesson.

In this practical you learn how to create your first interactive app—an app that enables user interaction. You create an app using the Empty Activity template. You also learn how to use the layout editor to design a layout, and how to edit the layout in XML. You need to develop these skills so you can complete the other practicals in this course.

What you should already know

You should be familiar with:

  • How to install and open Android Studio.
  • How to create the HelloWorld app.
  • How to run the HelloWorld app.

What you'll learn

  • How to create an app with interactive behavior.
  • How to use the layout editor to design a layout.
  • How to edit the layout in XML.
  • A lot of new terminology. Check out the Vocabulary words and concepts glossary for friendly definitions.

What you'll do

  • Create an app and add two Button elements and a TextView to the layout.
  • Manipulate each element in the ConstraintLayout to constrain them to the margins and other elements.
  • Change UI element attributes.
  • Edit the app's layout in XML.
  • Extract hardcoded strings into string resources.
  • Implement click-handler methods to display messages on the screen when the user taps each Button.

2. App overview

The HelloToast app consists of two Button elements and one TextView. When the user taps the first Button, it displays a short message (a Toast) on the screen. Tapping the second Button increases a "click" counter displayed in the TextView, which starts at zero.

Here's what the finished app looks like:

Hello Toast App after tapping the Toast button

3. Task 1: Create and explore a new project

In this practical, you design and implement a project for the HelloToast app. A link to the solution code is provided at the end.

1.1 Create the Android Studio project

  1. Start Android Studio and create a new project with the following parameters:

Attribute

Value

Template

Empty Activity

Name

Hello Toast

Package name

com.example.hellotoast

Language

Java

Minimum SDK

API 21: Android 5.0 (Lollipop)

Use legacy android.support libraries

Unchecked

  1. Select Run > Run app or click the Run icon Run Icon in the toolbar to build and execute the app on the emulator or your device.

1.2 Explore the layout editor

Android Studio provides the layout editor for quickly building an app's layout of user interface (UI) elements. It lets you drag elements to a visual design and blueprint view, position them in the layout, add constraints, and set attributes. Constraints determine the position of a UI element within the layout. A constraint represents a connection or alignment to another view, the parent layout, or an invisible guideline.

Explore the layout editor, and refer to the figure below as you follow the numbered steps:

76af3429c6df2e78.png

  1. In the app > res > layout folder in the Project > Android pane, double-click the activity_main.xml file to open it, if it is not already open.
  2. Click the Design tab if it is not already selected. You use the Design tab to manipulate elements and the layout, and the Code tab to edit the XML code for the layout. The Split tab allows you to edit the code and view the layout at the same time.
  3. The Palette pane shows UI elements that you can use in your app's layout.
  4. The Component Tree pane shows the view hierarchy of UI elements. View elements are organized into a tree hierarchy of parents and children, in which a child inherits the attributes of its parent. In the figure above, the TextView is a child of the ConstraintLayout. You will learn about these elements later in this lesson.
  5. The design and blueprint panes of the layout editor showing the UI elements in the layout. In the figure above, the layout shows only one element: a TextView that displays "Hello World".
  6. The Attributes tab displays the Attributes pane for setting properties for a UI element.

Tip: See Building a UI with Layout Editor for details on using the layout editor, and Meet Android Studio for the full Android Studio documentation.

4. Task 2: Add View elements in the layout editor

In this task you create the UI layout for the HelloToast app in the layout editor using the ConstraintLayout features. You can create the constraints manually, as shown later, or automatically using the Autoconnect tool.

2.1 Examine the element constraints

Follow these steps:

  1. Open activity_main.xml from the Project > Android pane if it is not already open. If the Design tab is not already selected, click it. You can also select the Split tab to see how changes to the layout affect the XML and vice versa.

If there is no blueprint, click the Select Design Surface button click the Select Design Surface button [ICON HERE] in the toolbar and choose Design + Blueprint. [IMAGEINFO]: ic_blueprint_icon.png, Blueprint button in the toolbar and choose Design and Blueprint.

7f2cacdc7d434449.png

  1. The Autoconnect tool ensure that the tool is not disabled. [IMAGEINFO]: ic_autoconnect_enabled_icon.png, Autoconnect button is also located in the toolbar. It is enabled by default. For this step, ensure that the tool is not disabled.
  2. Click the zoom in button to zoom into the design and blueprint panes for a close-up look.
  3. Select TextView in the Component Tree pane. The "Hello World" TextView is highlighted in the design and blueprint panes and the constraints for the element are visible.
  4. Refer to the animated figure below for this step. Control+click the circular handle on the right side of the TextView to delete the horizontal constraint that binds the view to the right side of the layout. The TextView jumps to the left side because it is no longer constrained to the right side. To add back the horizontal constraint, click the same handle and drag a line to the right side of the layout.

Deleting and adding a constraint

In the blueprint or design panes, the following handles appear on the TextView element:

  • Constraint handle: To create a constraint as shown in the animated figure above, click a constraint handle, shown as a circle on the side of an element. Then drag the handle to another constraint handle, or to a parent boundary. A zigzag line represents the constraint.

Constraint handle

  • Resizing handle: To resize the element, drag the square resizing handles. The handle changes to an angled corner while you are dragging it.

Constraint handle

2.2 Add a Button to the layout

When enabled, the Autoconnect tool automatically creates two or more constraints for a UI element to the parent layout. After you drag the element to the layout, it creates constraints based on the element's position.

Follow these steps to add a Button:

  1. Start with a clean slate. The TextView element is not needed, so while it is still selected, press the Delete key or choose Edit > Delete. You now have a completely blank layout.
  2. Drag a Button from the Palette pane to any position in the layout. If you drop the Button in the top middle area of the layout, constraints may automatically appear. If not, you can drag constraints to the top, left side, and right side of the layout as shown in the animated figure below.

Adding a button with constraints

2.3 Add a second Button to the layout

  1. Drag another Button from the Palette pane to the middle of the layout as shown in the animated figure below. Autoconnect may provide the horizontal constraints for you (if not, you can drag them yourself).
  2. Drag a vertical constraint to the bottom of the layout (refer to the figure below).

Adding a second button with constraints

You can remove constraints from an element by selecting the element and hovering your pointer over it to show the Clear Constraints click the specific handle that sets the constraint. [IMAGEINFO]: ic_remove_constraints_button.png button. Click this button to remove all constraints on the selected element. To clear a single constraint, Control+click the specific handle that sets the constraint.

To clear all constraints in the entire layout, click the Clear All Constraints tool in the toolbar. This tool is useful if you want to redo all the constraints in your layout.

5. Task 3: Change UI element attributes

The Attributes pane offers access to all of the XML attributes you can assign to a UI element. You can find the attributes (known as properties) common to all views in the View class documentation.

In this task you enter new values and change values for important Button attributes, which are applicable to most View types.

3.1 Change the Button size

The layout editor offers resizing handles on all four corners of a View so you can resize the View quickly. You can drag the handles on each corner of the View to resize it, but doing so hardcodes the width and height dimensions. Avoid hardcoding sizes for most View elements, because hardcoded dimensions can't adapt to different content and screen sizes.

Instead, use the Attributes pane on the right side of the layout editor to select a sizing mode that doesn't use hardcoded dimensions. The Attributes pane includes a square sizing panel called the view inspector at the top. The symbols inside the square represent the height and width settings as follows:

Sizing panel in the Attributes pane

In the figure above:

  1. Height control. This control specifies the layout_height attribute and appears in two segments on the top and bottom sides of the square. The angles indicate that this control is set to wrap_content, which means the View will expand vertically as needed to fit its contents. The "0" indicates a standard margin set to 0dp.
  2. Width control. This control specifies the layout_width and appears in two segments on the left and right sides of the square. The angles indicate that this control is set to wrap_content, which means the View will expand horizontally as needed to fit its contents, up to a margin of 0dp.
  3. Attributes pane close button. Click to close the pane.

Follow these steps:

  1. Select the top Button in the Component Tree pane.
  2. Click the Attributes tab on the right side of the layout editor window.

8cbf4c610a464e4f.png

  1. Click the width control twice—the first click changes it to Fixed with straight lines, and the second click changes it to Match Constraints with spring coils, as shown in the animated figure below.

Changing the width and height attributes

As a result of changing the width control, the layout_width attribute in the Attributes pane shows the value match_constraint and the Button element stretches horizontally to fill the space between the left and right sides of the layout.

  1. Select the second Button, and make the same changes to the layout_width as in the previous step, as shown in the figure below.

Changing the width and height attributes for the second Button

As shown in the previous steps, the layout_width and layout_height attributes in the Attributes pane change as you change the height and width controls in the inspector. These attributes can take one of three values for the layout, which is a ConstraintLayout:

  • The match_constraint setting expands the View element to fill its parent by width or height—up to a margin, if one is set. The parent in this case is the ConstraintLayout. You learn more about ConstraintLayout in the next task.
  • The wrap_content setting shrinks the View element's dimensions so it is just big enough to enclose its content. If there is no content, the View element becomes invisible.
  • To specify a fixed size that adjusts for the screen size of the device, use a fixed number of density-independent pixels (dp units). For example, 16dp means 16 density-independent pixels.

Tip: If you change the layout_width attribute using its popup menu, the layout_width attribute is set to zero because there is no set dimension. This setting is the same as match_constraint— the view can expand as much as possible to meet constraints and margin settings.

3.2 Change the Button attributes

To identify each View uniquely within an Activity layout, each View or View subclass (such as Button) needs a unique ID. And to be of any use, the Button elements need text. View elements can also have backgrounds that can be colors or images.

The Attributes pane offers access to all of the attributes you can assign to a View element. You can enter values for each attribute, such as the android:id, backgroundTint, textColor, and text attributes.

The following animated figure demonstrates how to perform these steps:

  1. After selecting the first Button, edit the ID field at the top of the Attributes pane to button_toast for the android:id attribute, which is used to identify the element in the layout. When the Rename dialog box appears, select Refactor. This changes all instances of the ID across the project to the new name.
  2. Set the backgroundTint attribute to @color/purple_200. (As you enter @c, choices appear for easy selection.)

Tip: If you don't see an attribute you're looking for, try using the search function as demonstrated in the animated figure below.

  1. Set the textColor attribute to @android:color/black.
  2. Edit the text attribute to Toast.

Changing other UI element attributes

  1. Perform the same attribute changes for the second Button, using button_count as the ID, Count for the text attribute, and the same colors for the backgroundTint and text as the previous steps.

The color/purple_200 is one of the predefined theme base colors defined in the colors.xml resource file. The original default purple is used for the app bar. Using the base colors for other UI elements creates a uniform UI. You will learn more about app themes and Material Design in another lesson.

6. Task 4: Add a TextEdit and set its attributes

One of the benefits of ConstraintLayout is the ability to align or otherwise constrain elements relative to other elements. In this task you will add a TextView in the middle of the layout, and constrain it horizontally to the margins and vertically to the two Button elements. You will then change the attributes for the TextView in the Attributes pane.

4.1 Add a TextView and constraints

  1. As shown in the animated figure below, drag a TextView from the Palette pane to the upper part of the layout, and drag a constraint from the top of the TextView to the handle on the bottom of the Toast Button. This constrains the TextView to be underneath the Button.

Constraining the TextView to the Toast Button

  1. As shown in the animated figure below, drag a constraint from the bottom of the TextView to the handle on the top of the Count Button, and from the sides of the TextView to the sides of the layout. This constrains the TextView to be in the middle of the layout between the two Button elements.

Constraining the TextView to the Count Button and to the left and right margins

4.2 Set the TextView attributes

With the TextView selected, open the Attributes pane, if it is not already open. Set attributes for the TextView as described below. The attributes you haven't encountered yet are explained after the instructions:

  1. Set the ID to show_count.
  2. Change the horizontal and vertical view size controls (layout_width and layout_height) to match_constraint.
  3. Set the text to 0.
  4. Scroll down the pane to Common Attributes and expand the textAppearance attribute.
  5. Set the textSize to 160sp.
  6. Set the textColor to @color/purple_500.
  7. Set the textStyle to B (bold).
  8. Scroll down the pane to All Attributes, and set the background to #FFFF00 for a shade of yellow.
  9. Scroll down to gravity, expand gravity, and select center.
  • textSize: The text size of the TextView. For this lesson, the size is set to 160sp. The sp stands for scale-independent pixel, and like dp, is a unit that scales with the screen density and user's font size preference. Use dp units when you specify font sizes so that the sizes are adjusted for both the screen density and the user's preference.
  • textStyle: The text style, set to B (bold) in this lesson
  • gravity: The gravity attribute specifies how a View is aligned within its parent View or ViewGroup. In this step, you center the TextView to be centered within the parent ConstraintLayout.

You may notice that the background attribute is in the Common Attributes section for a Button, but in the All Attributes section for a TextView. The Attributes pane changes for each type of View: The most popular attributes for the View type appear in the Common Attributes, and the rest are listed in All Attributes.

7. Task 5: Edit the layout in XML

The Hello Toast app layout is nearly finished! However, an exclamation point appears next to each UI element in the Component Tree. Hover your pointer over these exclamation points to see warning messages, as shown below. The same warning appears for all three elements: hardcoded strings should use resources.

Viewing UI element warnings

The easiest way to fix layout problems is to edit the layout in XML. While the layout editor is a powerful tool, some changes are easier to make directly in the XML source code.

5.1 Open the XML code for the layout

For this task, open the activity_main.xml file if it is not already open, and click the Code tab 52b700072a3a9d1b.png at the top right of the layout editor.

The XML editor appears, replacing the design and blueprint panes. As you can see in the figure below, which shows part of the XML code for the layout, the warnings are highlighted—the hardcoded strings "Toast" and "Count". (The hardcoded "0" is also highlighted but not shown in the figure.) Hover your pointer over the hardcoded string "Toast" to see the warning message.

a5451463cf806a20.png

5.2 Extract string resources

Instead of hard-coding strings, it is a best practice to use string resources, which represent the strings. Having the strings in a separate file makes it easier to manage them, especially if you use these strings more than once. Also, string resources are mandatory for translating and localizing your app, because you need to create a string resource file for each language.

  1. Click once on the word "Toast"(the first highlighted warning).
  2. Click on the lightbulb that appears at the beginning of the line 99083466cd80afe2.pngand select Extract string resource from the popup menu.
  3. Enter button_label_toast for the Resource name.
  4. Click OK. A string resource is created in the res/values/strings.xml file, and the string in your code is replaced with a reference to the resource:

@string/button_label_toast

  1. Extract the remaining strings: button_label_count for "Count", and count_initial_value for "0".
  2. In the Project > Android pane, expand values within res, and then double-click strings.xml to see your string resources in the strings.xml file:
<resources>
    <string name="app_name">Hello Toast</string>
    <string name="button_label_toast">Toast</string>
    <string name="button_label_count">Count</string>
    <string name="count_initial_value">0</string>
</resources>
  1. You need another string to use in a subsequent task that displays a message. Add to the strings.xml file another string resource named toast_message for the phrase "Hello Toast!":
<resources>
    <string name="app_name">Hello Toast</string>
    <string name="button_label_toast">Toast</string>
    <string name="button_label_count">Count</string>
    <string name="count_initial_value">0</string>
    <string name="toast_message">Hello Toast!</string>
</resources>

Tip: The string resources include the app name, which appears in the app bar at the top of the screen if you start your app project using the Empty Template. You can change the app name by editing the app_name resource.

8. Task 6: Add onClick handlers for the buttons

In this task, you add a Java method for each Button in MainActivity that executes when the user taps the Button.

6.1 Add the onClick attribute and handler to each Button

A click handler is a method that is invoked when the user clicks or taps on a clickable UI element. In Android Studio you can specify the name of the method in the onClick field in the Design tab's Attributes pane. You can also specify the name of the handler method in the XML editor by adding the android:onClick property to the Button. You will use the latter method because you haven't yet created the handler methods, and the XML editor provides an automatic way to create those methods.

  1. With the XML editor open (the Code tab), find the Button with the android:id set to button_toast:
<Button
        android:id="@+id/button_toast"
        android:layout_width="0dp"
        ...
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
  1. Add the android:onClick attribute to the end of the button_toast element after the last attribute and before the /> end indicator:
android:onClick="showToast" />
  1. Click the red bulb icon that appears next to the attribute. Select Create ‘showToast(View)' in ‘MainActivity'.

If the red bulb icon doesn't appear, click the method name ("showToast"). Press Alt-Enter (Option-Enter on the Mac), select Create ‘showToast(view)' in MainActivity, and click OK.

This action creates a placeholder method stub for the showToast() method in MainActivity, and opens MainActivity.java.

package com.example.hellotoast;

import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
  }

  public void showToast(View view) {
  }
}
  1. Return to activity_main.xml and repeat the last two steps with the button_count Button. Add the android:onClick attribute to the end, and add the click handler:
android:onClick="countUp" />

The XML code for the UI elements within the ConstraintLayout now looks like this:

  <Button
      android:id="@+id/button_toast"
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      android:backgroundTint="@color/purple_200"
      android:text="@string/button_label_toast"
      android:textColor="@android:color/black"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintHorizontal_bias="0.498"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toTopOf="parent"
      android:onClick="showToast"/>
  <Button
      android:id="@+id/button_count"
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      android:backgroundTint="@color/purple_200"
      android:text="@string/button_label_count"
      android:textColor="@android:color/black"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      android:onClick="countUp" />
  <TextView
      android:id="@+id/show_count"
      android:textStyle="bold"
      android:layout_width="0dp"
      android:layout_height="0dp"
      android:background="#FFFF00"
      android:gravity="center"
      android:text="@string/count_initial_value"
      android:textSize="160sp"
      app:layout_constraintBottom_toTopOf="@+id/button_count"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toBottomOf="@+id/button_toast" />

6.2 Edit the Toast Button handler

You will now edit the showToast() method—the Toast Button click handler in MainActivity—so that it shows a message. A Toast provides a way to show a simple message in a small popup window. It fills only the amount of space required for the message. The current activity remains visible and interactive. A Toast can be useful for testing interactivity in your app—add a Toast message to show the result of tapping a Button or performing an action.

Follow these steps to edit the Toast Button click handler:

  1. Locate the newly created showToast() method.
public void showToast(View view) {
}
  1. To create an instance of a Toast, call the makeText() factory method on the Toast class.
public void showToast(View view) {
  Toast toast = Toast.makeText(
}

This statement is incomplete until you finish all of the steps.

  1. Supply the context of the app Activity. Because a Toast displays on top of the Activity UI, the system needs information about the current Activity. When you are already within the context of the Activity whose context you need, use this as a shortcut.
Toast toast = Toast.makeText(this, 
  1. Supply the message to display, such as a string resource (the toast_message you created in a previous step). The string resource toast_message is identified by R.string.
Toast toast = Toast.makeText(this, R.string.toast_message, 
  1. Supply a duration for the display. For example, Toast.LENGTH_SHORT displays the toast for a relatively short time.
Toast toast = Toast.makeText(this, R.string.toast_message, 
                                          Toast.LENGTH_SHORT);

The duration of a Toast display can be either Toast.LENGTH_LONG or Toast.LENGTH_SHORT. The actual lengths are about 3.5 seconds for the long Toast and 2 seconds for the short Toast.

  1. Show the Toast by calling show(). The following is the entire showToast() method:
public void showToast(View view) {
  Toast toast = Toast.makeText(this, R.string.toast_message, 
                                          Toast.LENGTH_SHORT);
  toast.show();
}

Run the app and verify that the Toast message appears when the Toast button is tapped.

2b75e67fd54b7ed6.png

6.3 Edit the Count Button handler

You will now edit the countUp() method—the Count Button click handler in MainActivity—so that it displays the current count after Count is tapped. Each tap increases the count by one.

The code for the handler must:

  • Keep track of the count as it changes.
  • Send the updated count to the TextView to display it.

Follow these steps to edit the Count Button click handler:

  1. Locate the newly created countUp() method.
public void countUp(View view) {
}
  1. To keep track of the count, you need a private member variable. Each tap of the Count button increases the value of this variable. Enter the following, which will be highlighted in red and show a red bulb icon:
public void countUp(View view) {
  mCount++;
}

If the red bulb icon doesn't appear, select the mCount++ expression. The red bulb eventually appears.

  1. Click the red bulb icon and choose Create field ‘mCount' in ‘MainActivity' from the popup menu. This creates a private member variable at the top of MainActivity, and Android Studio assumes that you want it to be an integer (int):
public class MainActivity extends AppCompatActivity {
  private int mCount;
  1. Change the private member variable statement to initialize the variable to zero:
public class MainActivity extends AppCompatActivity {
  private int mCount = 0;
  1. Along with the variable above, you also need a private member variable for the reference of the show_count TextView, which you will add to the click handler. Call this variable mShowCount:
public class MainActivity extends AppCompatActivity {
  private int mCount = 0;
  private TextView mShowCount;
  1. Now that you have mShowCount, you can get a reference to the TextView using the ID you set in the layout file. In order to get this reference only once, specify it in the onCreate() method. As you will learn in another lesson, the onCreate() method is used to inflate the layout, which means to set the content view of the screen to the XML layout. You can also use it to get references to other UI elements in the layout, such as the TextView. Locate the onCreate() method in MainActivity:
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
}
  1. Add the findViewById statement to the end of the method:
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  mShowCount = (TextView) findViewById(R.id.show_count);
}

A View, like a string, is a resource that can have an id. The findViewById call takes the ID of a view as its parameter and returns the View. Because the method returns a View, you have to cast the result to the view type you expect, in this case (TextView).

  1. Now that you have assigned to mShowCount the TextView, you can use the variable to set the text in the TextView to the value of the mCount variable. Add the following to the countUp() method:
if (mShowCount != null) {
  mShowCount.setText(Integer.toString(mCount));
}

The entire countUp() method now looks like this:

public void countUp(View view) {
  mCount++;
  if (mShowCount != null) {
    mShowCount.setText(Integer.toString(mCount));
  }
}
  1. Run the app to verify that the count increases when you tap the Count button.

The Hello Toast app showing the count as you tap the Count button

Tip: For an in-depth tutorial on using ConstraintLayout, see the Codelab Using ConstraintLayout to design your views.

9. Solution code

Android Studio project: HelloToast

10. Coding challenge

The HelloToast app looks fine when the device or emulator is vertically oriented. However, if you switch the device or emulator to horizontal orientation, the Count Button may overlap the TextView along the bottom as shown in the figure below.

The Hello Toast app in horizontal orientation

Challenge: Change the layout so that it looks good in both horizontal and vertical orientations:

  1. On your computer, make a copy of the HelloToast project folder and rename it to HelloToastChallenge.
  2. Open HelloToastChallenge in Android Studio and refactor it. (See Appendix: Utilities for instructions on copying and refactoring a project.)
  3. Change the layout so that the Toast Button and Count Button appear on the left side, as shown in the figure below. The TextView appears next to them, but only wide enough to show its contents. (Hint: Use wrap_content.)
  4. Run the app in both horizontal and vertical orientations.

The Hello Toast app with a different layout

The Hello Toast app with a different layout in horizontal orientation

Challenge solution code

Android Studio project: HelloToastChallenge

11. Summary

View, ViewGroup, and layouts:

  • All UI elements are subclasses of the View class and therefore inherit many properties of the View superclass.
  • View elements can be grouped inside a ViewGroup, which acts as a container. The relationship is parent-child, in which the parent is a ViewGroup, and the child is a View or another ViewGroup.
  • The onCreate() method is used to inflate the layout, which means to set the content view of the screen to the XML layout. You can also use it to get references to other UI elements in the layout.
  • A View, like a string, is a resource that can have an id. The findViewById call takes the ID of a view as its parameter and returns the View.

Using the layout editor:

  • Click the Design tab to manipulate elements and the layout, and the Code tab to edit the XML code for the layout.
  • In the Design tab, the Palette pane shows UI elements that you can use in your app's layout, and the Component Tree pane shows the view hierarchy of UI elements.
  • The design and blueprint panes of the layout editor show the UI elements in the layout.
  • The Attributes tab displays the Attributes pane for setting properties for a UI element.
  • Constraint handle: Click a constraint handle, shown as a circle on each side of an element, and then drag to another constraint handle or to the parent boundary to create a constraint. The constraint is represented by the zigzag line.
  • Resizing handle: You can drag the square resizing handles to resize the element. While dragging, the handle changes to an angled corner.
  • When enabled, the Autoconnect tool automatically creates two or more constraints for a UI element to the parent layout. After you drag the element to the layout, it creates constraints based on the element's position.
  • You can remove constraints from an element by selecting the element and hovering your pointer over it to show the Clear Constraints click the specific handle that sets the constraint. [IMAGEINFO]: remove_constraints_button.png button. Click this button to remove all constraints on the selected element. To clear a single constraint, click the specific handle that sets the constraint.
  • The Attributes pane offers access to all the XML attributes you can assign to a UI element. It also includes a square sizing panel called the view inspector at the top. The symbols inside the square represent the height and width settings.

Setting layout width and height:

The layout_width and layout_height attributes change as you change the height and width size controls in the view inspector. These attributes can take one of three values for a ConstraintLayout:

  • The match_constraint setting expands the view to fill its parent by width or height—up to a margin, if one is set.
  • The wrap_content setting shrinks the view dimensions so the view is just big enough to enclose its content. If there is no content, the view becomes invisible.
  • Use a fixed number of dp ( density-independent pixels) to specify a fixed size, adjusted for the screen size of the device.

Extracting string resources:

Instead of hard-coding strings, it is a best practice to use string resources, which represent the strings. Follow these steps:

  1. Click once on the hardcoded string to extract, press Alt-Enter (Option-Enter on the Mac), and choose Extract string resource from the popup menu.
  2. Set the Resource name.
  3. Click OK. This creates a string resource in the res/values/string.xml file, and the string in your code is replaced with a reference to the resource: @string/button_label_toast

Handling clicks:

  • A click handler is a method that is invoked when the user clicks or taps on a UI element.
  • Specify a click handler for a UI element such as a Button by entering its name in the onClick field in the Design tab's Attributes pane, or in the XML editor by adding the android:onClick property to a UI element such as a Button.
  • Create the click handler in the main Activity using the View parameter. Example: public void showToast(View view) {/...}.
  • You can find information on all Button properties in the Button class documentation, and all the TextView properties in the TextView class documentation.

Displaying Toast messages:

A Toast provides a way to show a simple message in a small popup window. It fills only the amount of space required for the message. To create an instance of a Toast, follow these steps:

  1. Call the makeText() factory method on the Toast class.
  2. Supply the context of the app Activity and the message to display (such as a string resource).
  3. Supply the duration of the display, for example Toast.LENGTH_SHORT for a short period. The duration can be either Toast.LENGTH_LONG or Toast.LENGTH_SHORT.
  4. Show the Toast by calling show().

12. Related concept

The related concept documentation is in 1.2: Layouts and resources for the UI.

13. Learn more

Android developer documentation:

Other:

14. Next codelab

The next codelab is Android fundamentals 1.2 Part B: The layout editor.