In this codelab, you'll learn how to build and run your first Android app in Kotlin. If you're looking for the Java version of this codelab, you can go here. Kotlin is a statically typed programming language that runs on the JVM and is completely interoperable with Java. Kotlin is an officially supported language for developing Android apps, along with Java.

What you'll learn

What you must know already

This codelab is written for programmers and assumes you know either Java or Kotlin. If you are an experienced programmer and you are adept at reading code, you will likely be able to follow this codelab even if you don't have much experience with Kotlin.

Use Kotlin and Android Studio to write Android apps

You write Android apps in Kotlin or Java using an IDE called Android Studio. Based on JetBrains' IntelliJ IDEA software, Android Studio is an IDE designed specifically for Android development. To create applications in Kotlin, we recommend that you install Android Studio 3.0 or higher.

To work through this codelab, you will need a computer that can run Android Studio (or already has Android Studio installed).

You use Android Studio to build Android apps. Based on JetBrains' IntelliJ IDEA software, Android Studio is an IDE designed specifically for Android development.

Android Studio is available for Windows, Mac, and Linux computers. The installation is similar for all platforms. Any differences are noted in the sections below.

If you are using a computer that already has Android Studio installed, go to the next task, Create your first project.

Otherwise you'll first check that you have the correct Java version (which is a requirement for Android Studio) and then install Android Studio.

What you'll learn

Install Java if needed

To get up and running with Android Studio, you may need to install the Java Development Kit - Java 7 or better.

Install the Java Development Kit

  1. On your computer, open a terminal window.
  2. Type java -version

The output includes this line:

Java(™) SE Runtime Environment (build 1.X.0_05-b13)

X is the version number to look at.

To download the Java Standard Edition Development Kit (JDK):

  1. Go to Oracle Java SE Downloads.
  2. Click the Java SE Downloads icon to open the Java SE Development Kit 8 Downloads page.
  3. In the box for the latest Java SE Development Kit, accept the License Agreement. Then download the version appropriate for your computer.
  1. Install the development kit. It should only take a few minutes.
  2. When the installation has finished, open a terminal window and type java -version again to verify that installation has been successful.
  3. Set the JAVA_HOME environment variable to the installation directory of the JDK (see machine-specific instructions below).

Set JAVA_HOME

Windows:

Set JAVA_HOME to the installation location:

  1. Start > Control Panel > System > Advanced System Settings > Environment Variables System Variables > New
  1. If the variable already exists, update it to your version of the JDK.

Verify your JAVA_HOME variable from a cmd.exe terminal: echo %JAVA_HOME%.

For more details, see Installing the JDK Software and Setting JAVA_HOME.

Mac:

Set JAVA_HOME to the installation location:

  1. Open Terminal.
  2. Navigate to your home directory using cd
  3. Open the file ~/.bash_profile which is a configuration file for your terminal
  4. Add the following command to the file:
    export JAVA_HOME=$(/usr/libexec/java_home)
  5. Reload the configuration file using:
    source ~/.bash_profile
  6. Enter echo $JAVA_HOME to confirm the path.

Linux:

Set JAVA_HOME to the installation location:

See Installing the JDK Software and Setting JAVA_HOME.

Install Android Studio

  1. Go to the Android Studio preview page and install Android Studio 3.0. Android Studio 3.0 or higher supports Kotlin. You can follow the instructions to download and install Android Studio.
  1. After finishing the install, the Setup Wizard downloads and installs additional components. Be patient, because this might take some time depending on your Internet speed, and some of the steps may seem redundant.
  2. When the download completes, Android Studio starts, and you are ready to create your first project.

Learn more about installing Android Studio

In this step, you will create a new Android project for your first app. This simple app displays the string "Hello World" on the screen of the Android virtual or physical device.

Here's what the finished app will look like:

What you'll learn

Create a new project

  1. Open Android Studio.
  2. In the main Welcome to Android Studio dialog, click Start a new Android Studio project.
  3. In the New Project dialog, give your application a name such as My First App.
  4. Accept the default example domain.
  5. Check the box that says Include Kotlin support.
  6. Accept the default project location. Click Next.
  7. In the Target Android Devices dialog, accept the defaults. Click Next.
  8. Select Empty Activity. Click Next.
  9. In the Customize the Activity dialog, accept the defaults.
  10. Click Finish.


After these steps, Android Studio:

The Android Studio window should look similar to the following diagram:

Explore the project structure and layout

You can look at the hierarchy of the files for your app in multiple ways.

  1. Click the app (1) folder to expand the hierarchy of files. (See 1 in the screenshot.)
  2. Click Project (2). You might need to select View > Tool Buttons to see this option.
  3. The current Project view selection is Project > Android. Click Android (3) to explore the other Project views that are available.

In the Project > Android view you see three top-level folders below your app folder: manifests, java, and res.

  1. Expand the manifests folder.

    This folder contains AndroidManifest.xml. This file describes all the components of your Android app and is read by the Android runtime system when your app is executed.
  2. Expand the java folder. All your Kotlin and Java language files are organized here. The java folder contains three subfolders:

    com.example.android.myfirstapp (or the domain name you have specified): This folder contains the Kotlin and Java source code files for your app.

    com.example.android.myfirstapp (androidTest): This folder is where you would put your instrumented tests. It starts out with a skeleton test file.

    com.example.android.myfirstapp (test): This folder is where you would put your unit tests. It starts out with a skeleton unit test file.
  3. Expand the res folder. This folder contains all the resources for your app, including images, layout files, strings, icons, and styling. It includes these subfolders:

    drawable: All your app's images will be stored in this folder.

    layout: This folder contains the layout files for your activities. Currently your app has one activity that has a layout file called activity_main.xml.

    mipmap: This folder contains the launcher icons for your app.

    values: Contains resources, such as strings and colors, used in your app.

Create a virtual device (emulator)

In this task, you will use the Android Virtual Device (AVD) manager to create a virtual device (also known as an emulator) that simulates the configuration for a particular type of Android device.

The first step is to create a configuration that describes the virtual device.

  1. In Android Studio, select Tools > Android > AVD Manager, or click the AVD Manager icon in the toolbar.
  2. Click +Create Virtual Device. (If you have created a virtual device before, the window shows all of your existing devices and the +Create Virtual Device button is at the bottom.) The Select Hardware dialog shows a list of preconfigured hardware device definitions.
  3. Choose a device definition, such as Nexus 5, and click Next.
  4. In the System Image dialog, from the Recommended tab, choose the latest release.
  5. If a Download link is visible next to a latest release, it is not installed yet, and you need to download it. If necessary, click the link to start the download, and click Next when it's done.
  6. In the next dialog box, accept the defaults, and click Finish.
  7. If the Your Virtual Devices AVD Manager window is still open, go ahead and close it.

Run your app on an emulator

  1. In Android Studio, select Run > Run app or click the Run icon in the toolbar.

  1. In the Select Deployment Target dialog, under Available Virtual Devices, select the virtual device that you just configured and click OK.

The emulator starts and boots just like a physical device. Depending on the speed of your computer, this may take a while. You can look in the small horizontal status bar at the very bottom of Android Studio for messages to see the progress.

Messages that might appear briefly in the status bar

Gradle build running

Waiting for target device to come on line

Installing APK

Launching activity

Once your app builds and the emulator is ready, Android Studio uploads the app to the emulator and runs it. You should see your app as shown in the following screenshot.

Run your app on a device (if you have one)

What you need:

Run your app on a device

To let Android Studio communicate with your device, you must turn on USB Debugging on your Android device.

On Android 4.2 and higher, the Developer options screen is hidden by default. To show Developer options and enable USB Debugging:

  1. On your device, open Settings > About phone and tap Build number seven times.
  2. Return to the previous screen (Settings). Developer options appears at the bottom of the list. Tap Developer options.
  3. Enable USB Debugging.

Now you can connect your device and run the app from Android Studio.

  1. Connect your device to your development machine with a USB cable. On the device, you might need to agree to allow USB debugging from your development device.
  2. Click Run in the toolbar at the top of the window. (You might need to select View > Toolbar to see this option.) The Select Deployment Target dialog opens with the list of available emulators and connected devices.
  3. Select your device, and click OK.

Android Studio installs the app on your device and runs it.

Troubleshooting

If you're stuck, quit Android Studio and restart it.

If Android Studio does not recognize your device, try the following:

  1. Disconnect your device from your development machine and reconnect it.
  2. Restart Android Studio.

If your computer still does not find the device or declares it "unauthorized":

  1. Disconnect the device.
  2. On the device, open Settings->Developer Options.
  3. Tap Revoke USB Debugging authorizations.
  4. Reconnect the device to your computer.
  5. When prompted, grant authorizations.

You may need to install the appropriate USB driver for your device. See the Using Hardware Devices documentation.

Check the latest Android Studio documentation.

Generally each screen in your Android app is associated with one Java or Kotlin class known as an activity. The single screen with "Hello World" displayed is created by one activity, called MainActivity.kt. This was generated for you when you created your new project. Each visible activity in an Android app has a layout that defines the user interface for the activity. Android Studio has a layout editor where you can create and define layouts.

Layouts are defined in XML. The layout editor lets you define and modify your layout either by coding XML or by using the interactive visual editor. You can switch between editing your layout in XML and in the visual design editor as often as you like.

Every element in a layout is a view. In this task, you will explore some of the panels in the layout editor, and you will learn how to change property values for views.

What you'll learn

Open the layout editor

  1. Find and open the layout folder.



  2. Double-click activity_main.xml.

    The panel on the right, called the layout editor, displays the content of this file.
  3. At the bottom of the panel, notice the two tabs: Design and Text. Open the Text tab.



    The XML code that defines the layout appears in the Text tab.

  4. Open the Design tab to display the design editor.



  5. At the top right of the design editor you see the + and - buttons for zooming in and out. Use these buttons to adjust the view, or click the Zoom to Fit Screen button (to the right of the zoom buttons) so that both panels fit reasonably on your screen.



    In this screenshot, the design layout on the left shows how your app appears on the device. The blueprint layout, shown on the right, is a schematic view of the layout.
  6. Practice using the layout icons in the top left of the design toolbar to display the design view, the blueprint view, and both views side by side.
  7. Use the orientation icon to change the orientation of the layout.



  8. Use the device menu to view the layout on different devices.



Explore and resize the Component Tree

  1. Look at the Component Tree on the bottom left of the Design tab.



    This panel shows the hierarchy of views in your layout.
  2. Adjust the sides of the panels so that you can see everything in the Component Tree.

  3. Click the Close Panel Icon at the top right of the Component Tree.

    The Component Tree panel closes.
  4. Bring back the Component Tree panel by clicking the vertical label "Component Tree" on the left.



    Now that you know how to resize, close, and open the Component Tree panel, it's time to explore view hierarchies.

Explore view hierarchies

  1. In the Component Tree, notice that the root of the view hierarchy is a ConstraintLayout view.

    Every layout must have a root view that contains all the other views. The root view is always a view group, which is a view that contains other views. A ConstraintLayout is one example of a view group.
  2. Notice that the ConstraintLayout contains a TextView.


  3. View the XML code for the layout by clicking the Text tab at the bottom of the Design tab.

  4. In the XML code, notice that the root element is <android.support.constraint.ConstraintLayout>. The root element contains a single <TextView> element.

<android.support.constraint.ConstraintLayout
  ... >

   <TextView
      ...  />

</android.support.constraint.ConstraintLayout>

Change property values

  1. In the Text tab, examine the properties in the TextView element.

    For now, don't worry about any tools:layout properties; you will explore those in detail soon.

<TextView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Hello World!"
   ... />
  1. Change the value of the text property to whatever you like.
  2. Switch back to the Design tab.
  3. Select the TextView in the Component Tree.


  1. Look at the Properties panel on the right.



  1. In the text field of the TextView in the Properties panel, change the value of the text again and press Enter to complete the selection


  2. Switch back to the Text tab to verify that the text changed in the XML.

  3. Run the app to see the change.



Change text display properties

  1. In the Design tab, expand the textAppearance field for the TextView.



  2. Change some of the text properties. For example, change the font family, increase the text size, and select bold style. (You might need to scroll the panel to see all the fields.)
  3. Change the text color. Click in the textColor field, and enter g.

    A menu pops up with possible completion values. This list contains pre-defined colors. You will learn how to define your own colors soon.



  4. Select @android:color/darker_gray and press Enter.



  5. In the Text tab, view the XML for the TextView. You see that the new properties have been added.



  1. Run the app again.




Display all properties

  1. Return to the Design tab. In the top right of the Properties panel, click the View all properties icon. If you don't see any properties, make sure the TextView is still selected in the Component Tree.





    The Properties panel updates to show all the properties for the TextView.



  2. Scroll through the list to get an idea of the properties you could set for a TextView.

So far you have learned how to change property values. Next, you will learn how to create resources. Using resources enables you to use the same values in multiple places, or to define values and have the UI update automatically whenever the value is changed.

What you'll learn

Extract resources

  1. In the Project panel on the left, double-click on res > values > strings.xml.



    The strings.xml file opens in the editor. Don't worry if you see a notice about editing translations.

    This file contains the <resources> element, which in turn contains a single <string> element specifying the name of the app.
  2. Go back to the activity_main.xml layout file. Make sure you are in the Text tab. Notice that the text property is highlighted.



  3. Click the highlighted code. A light bulb appears on the left.



  4. Click the lightbulb. In the menu that pops up, select Extract string resource.



  5. In the dialog box that appears, the resource name reflects the current value of the string. Change the resource name to hello_world_text and click OK.



  6. In the Text tab, notice that the value of the android:text property has changed to @string/hello_world_text.



  7. Go to the strings.xml file. Notice that a new string resource has been added, named hello_world_text.



  8. In strings.xml, change the value of the hello_world_text string resource to Hello Universe (or to a string of your own choosing).


  9. Go back to activity_main.xml. You see that the value of the text property is still @string/hello_world_text.
  10. Run the app to make sure it displays as you expect it to. (Test early, test often.)

You now know how to create new string resources by extracting them from existing field values. You can also add new resources to the strings.xml file manually.

Add color resources

Next up, you'll learn how to add new color resources.

Change the text color and background of the TextView

  1. In the Project panel on the left, double-click on res > values > colors.xml to open the color resource file.




    The colors.xml file opens in the editor. So far, three colors have been defined.
  2. Go back to activity_main.xml in the Text tab, so you can see the XML code for the layout.
  3. Add a new property to the TextView called android:background, and start typing to set its value to @color.

    A menu pops up offering the pre-defined color resources:



  4. Choose @color/colorPrimaryDark.
  5. Change the property android:textColor and give it a value of @android:color/white.

    The Android framework defines a range of colors, including white, so you don't have to define white yourself.
  6. Go back to the Design tab in activity_main.xml. Hide the Properties panel if it's cluttering your view.



    You see that the TextView now has a dark blue background, and the text is displayed in white.


Add a new color to use as the screen background color

  1. Back in colors.xml, add a new color resource:

<color name="screenBackground">#FFEE58</color>


This color is yellow.

  1. Go back to the Design tab in activity_main.xml. In the Component Tree, select the ConstraintLayout.



  2. In the Properties panel, display all properties. Select the background property and press Enter. Type "c" in the field that appears.
  3. In the menu of colors that appears, select @color/screenBackground. Press Enter to complete the selection.


  4. Double-click the yellow patch to the left of the color value in the background field.




    The Colors page of the Resources editor opens, showing the list of colors defined in your project as well as colors defined by the Android framework. It also offers an interactive color chooser.

  5. Feel free to change the value of the screenBackground color, but make sure that the final color is noticeably different from the colorPrimary and colorPrimaryDark colors.

Explore width and height properties

Now that you have a new screen background color, you will use it to explore the effects of changing width and height properties of views.

  1. Go to the Design tab for activity_main.xml. In the Component Tree, select the ConstraintLayout.



  2. In the Properties panel, show the minimized view of the properties. Toggle the View all properties icon if you need to.


    The layout_width and layout_height properties are both set to match_parent. The ConstraintLayout is the root view, so the "parent" layout size is effectively the size of the screen on the device. The ConstraintLayout will be the same width and height as the screen.
  1. In the Design tab, notice that the entire background of the screen uses the screenBackground color.



  2. Now select the TextView and change both the width and height to match_parent.

    The TextView fills the entire screen because its width and height are the same as the ConstraintLayout, which in turn fills the entire screen.

  3. Explore what happens if the width is match_parent and the height is wrap_content and vice versa.
  4. Set both the width and height of the TextView back to wrap_content.

In this task, you will add three buttons to your user interface, as shown here.


What you'll learn

View constraint properties

  1. In the Text tab, look at the constraint properties for the TextView.



    These properties define the position of the TextView. Read them carefully.

    You can constrain the top, bottom, left, and right of a view to the top, bottom, left, and right of other views. In this case, the only other view is the ConstraintLayout root view, which is the parent of this TextView.
  2. In the Design tab, select the TextView in the Component Tree and look at the Constraint Inspector at the top of the Properties panel.



    Each of the blue dots represents a constraint.
  3. Notice that the blueprint view also shows the constraints when a particular view is selected. Move the cursor over the design view, and it shows the constraints too.



Add buttons and constrain their positions

To learn how to use constraints to connect the positions of views to each other, you will add three buttons to the layout.

  1. Notice the Palette at the top left of the layout editor. Move the sides so that you can see many of the items in the palette.

  2. Scroll the listed items to get an idea of what's available.
  3. Select Button, which is near the top, and drag and drop it onto the design view, placing it underneath the TextView.

Add a constraint to the button

You will now constrain the top of the button to the bottom of the TextView.

  1. Move the cursor over the circle in the middle of the top of the button.


  2. Drag the circle at the top of the button onto the circle at the bottom of the TextView.



    The button moves up to sit just below the TextView. The top of the button is now constrained to the bottom of the TextView.


  1. Take a look at the Constraint inspector in the Properties panel. It shows one constraint for the button.
  2. In the Text tab, take a look at the XML code for the button. It includes the attribute that constrains the top of the button to the bottom of the TextView, and also has a top margin, which was added automatically.


Add a second button

  1. Add another button to the layout, and drop it anywhere. (Don't worry if it flies off somewhere else in the layout!)
  2. Play around with the positions and constraints of the two buttons. Try adding and deleting constraints.
  1. When you're comfortable with adding and deleting constraints, add constraints to get the buttons into their final position. The left button should be on the left of the screen, and the right button should be on the right of the screen. Vertically, both buttons appear between the TextView and the bottom of the screen (see the picture below).

    Do this by adding constraints to the two buttons so that:

Add a third button

You will add a third button that will ultimately sit between the two existing buttons.

  1. Add a third button.
  2. Constrain the left and right sides of the new button to its neighboring buttons.
  3. Constrain the top and bottom of the new button the same as the existing buttons. In other words, the top of the new button is constrained to the bottom of the TextView. The bottom is constrained to the bottom of the screen.
  4. Examine the XML code in the Text tab. Do any of the buttons have the attribute app:layout_constraintVertical_bias? It's OK if you do not see that constraint.

    The "bias" constraints allows you to tweak the position of a view to be more on one side than the other when both sides are constrained in opposite directions. For example, if both the top and bottom sides of a view are constrained to the top and bottom of the screen, you can use a vertical bias to place the view more towards the top than the bottom.
  5. The XML code for the new button most likely appears after the other two buttons in the XML file. Move the code for the new button so it is in between the other two buttons, so that the order of the buttons in the XML file reflects the order they appear in the design. This change does not affect the functionality or the appearance of the layout, but it will help you correlate the views in the Text tab to the views in the Design tab.

Here is the XML code for the layout. Your layout might have different margins and perhaps some different vertical or horizontal bias constraints.The exact values of the attributes for the appearance of the TextView might be different for you.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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"
   android:background="@color/screenBackground"
   tools:context="com.example.android.myfirstapp.MainActivity">

   <TextView
       android:id="@+id/textView"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
        android:background="@color/colorPrimaryDark"
       android:fontFamily="sans-serif"
       android:text="@string/hello_world_text"
       android:textAlignment="center"
       android:textColor="@android:color/white"
       android:textSize="30sp"
       android:textStyle="bold"
       app:layout_constraintBottom_toBottomOf="parent"
       app:layout_constraintLeft_toLeftOf="parent"
       app:layout_constraintRight_toRightOf="parent"
       app:layout_constraintTop_toTopOf="parent"
    />

   <Button
       android:id="@+id/button"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Button"
       android:layout_marginLeft="8dp"
       app:layout_constraintLeft_toLeftOf="parent"
       app:layout_constraintBottom_toBottomOf="parent"
       android:layout_marginBottom="8dp"
       android:layout_marginTop="8dp"
       app:layout_constraintTop_toBottomOf="@+id/textView" />

   <Button
       android:id="@+id/button3"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Button"
       app:layout_constraintBottom_toBottomOf="parent"
       android:layout_marginBottom="8dp"
       android:layout_marginTop="8dp"
       app:layout_constraintTop_toBottomOf="@+id/textView"
       app:layout_constraintRight_toLeftOf="@+id/button2"
       android:layout_marginRight="8dp"
       app:layout_constraintLeft_toRightOf="@+id/button"
       android:layout_marginLeft="8dp" />

   <Button
       android:id="@+id/button2"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Button"
       android:layout_marginRight="8dp"
       app:layout_constraintRight_toRightOf="parent"
       app:layout_constraintBottom_toBottomOf="parent"
       android:layout_marginBottom="8dp"
       android:layout_marginTop="8dp"
       app:layout_constraintTop_toBottomOf="@+id/textView" />

</android.support.constraint.ConstraintLayout>

Get your UI ready for the next task

The next task is to make the buttons do something when they are pressed. Before learning how to make your buttons interactive, finish getting the UI ready.

  1. Change the text of the TextView to show 0 (the number zero).
  2. Change the text and id of the buttons. You can edit the XML code in the Text tab, or you can set the property values in the Properties panel in the design editor. Set the Text and id as shown here:

Button

Text

id

Left button

Toast

@+id/toast_button

Middle button

Count

@+id/count_button

Right button

Random

@+id/random_button

Fix errors if necessary

If you edited the XML for the layout, the XML code for the middle button, which is now the Count button, shows some errors. Also the layout is messed up in the Design tab.

The errors occur because the buttons on the left and right have changed their id.

  1. If you have these errors, fix them by updating the id of the buttons in the constraints that are underlined in red.
app:layout_constraintRight_toLeftOf="@+id/toast_button"
app:layout_constraintLeft_toRightOf="@+id/random_button"

Update the appearance of the buttons and the TextView

Your app's layout is now basically complete, but it's appearance can be improved by a few small changes.

Add new color resources

  1. In colors.xml, change the value of screenBackground to #2196F3, which is a blue shade in the Material Design palette.
  2. Add a new color named "buttonBackground." Use the value #BBDEFB, which is a lighter shade in the blue palette.
<color name="buttonBackground">#BBDEFB</color>

Add a background color for the buttons

  1. In the layout, add a background color to each of the buttons. (You can either edit the XML or use the Properties panel, whichever you prefer.)
android:background="@color/buttonBackground"

Change the margins of the left and right buttons

  1. Give the left button a left margin of 24dp and give the right button a right margin of 24dp.
android:layout_marginLeft="24dp"
android:layout_marginRight="24dp"

Update the appearance of the TextView

  1. Remove the background color of the TextView, either by clearing the value in the Properties panel or by removing the android:background attribute from the XML code.

    When you remove the background, the view background becomes transparent.
  2. Increase the text size of the TextView to 72sp.
android:textSize="72sp"
  1. Change the font-family of the TextView to sans-serif (if it's not already).
  2. Add an app:layout_constraintVertical_bias property to the TextView, to bias the position of the view upwards a little so that it is more evenly spaced vertically in the screen. Feel free to adjust the value of this constraint as you like. (Check in the Design tab to see how the layout looks).
app:layout_constraintVertical_bias="0.3"

Run your app

If you implemented all the updates, your app will look like the following figure. If you used different colors and fonts, then your app will look a bit different.



You have added buttons to your app's main screen, but currently the buttons do nothing. You'll fix that in the next task.

.

You have added buttons to your app's main screen, but currently the buttons do nothing. In this task, you will make your button respond when the user presses the buttons.

First you will make the Toast button show a pop-up message called a toast. Next you will make the Count button update the number that is displayed in the TextView.

What you'll learn

Enable auto imports

Before adding behavior to your buttons, you will enable auto-imports so that Android Studio automatically imports any classes that are needed by the Kotlin code.

  1. In Android Studio, open the settings editor. Go to File > Other Settings > Default Settings.




  2. Select Auto Imports. In the Java section, make sure Add Unambiguous Imports on the fly is checked.

  3. Close the settings editor.

Show a toast

In this step, you will add a method to the Toast button to show a toast when the user presses it. A toast is a short message that appears briefly at the bottom of the screen.

  1. Open MainActivity.kt. (Expand app > java > com.example.android.myfirstapp to find MainActivity).

    This class has only one method, onCreate(). The onCreate() method executes when the activity starts.
  2. Examine the onCreate() method. Notice the line that calls setContentView(). This line sets the layout of the activity to activity_main.xml.
setContentView(R.layout.activity_main);
  1. Add a new method called toastMe() to the MainActivity class. The toastMe() method takes a single argument of a View. This is the view that receives the click event.

    The method creates and shows a toast. Here is the code:
fun toastMe(view: View) {
  // val myToast = Toast.makeText(this, message, duration);
  val myToast = Toast.makeText(this, "Hello Toast!", Toast.LENGTH_SHORT)
  myToast.show()
}
  1. In the Text tab for the layout file, add an android:onClick property to the Toast button. Set the value to toastMe.
android:onClick="toastMe"
  1. Run the app and press the Toast button. Do you see the toasty message at the bottom of the screen?

You have learned that to make a view interactive you need to:

Make the Count button update the number on the screen

The method that shows the toast is very simple; it does not interact with any other views in the layout. The next step is to add behavior to your layout to find and update other views.

Update the Count button so that when it is pressed, the number on the screen increases by 1:

  1. In the layout file, notice the id for the TextView:
<TextView
   android:id="@+id/textView"
  1. In ActivityMain.kt, add a method countMe() in the MainActivity class. This method will be invoked when the Count button is clicked, so it is public, has no return statement, and has a single View argument.
fun countMe (view: View) {
  
}
  1. Use the predefined findViewById() method to get the TextView that shows the count. This method returns a View, so you must cast the result to a TextView. Specify the id of the view to get.
fun countMe (view: View) {
   // Get the text view
   val showCountTextView = findViewById(R.id.textView) as TextView
}
  1. Get the value of the showCountTextView.
fun countMe (view: View) {
   // Get the text view
   val showCountTextView = findViewById(R.id.textView) as TextView
  
   // Get the value of the text view.
   val countString = showCountTextView.text.toString()

}
  1. Convert the value to a number, and increment it.
fun countMe (view: View) {
   // Get the text view
   val showCountTextView = findViewById(R.id.textView) as TextView

   // Get the value of the text view.
   val countString = showCountTextView.text.toString()

   // Convert value to a number and increment it
   var count: Int = Integer.parseInt(countString)
   count++
}
  1. Display the new value in the TextView.
fun countMe (view: View) {
   // Get the text view
   val showCountTextView = findViewById(R.id.textView) as TextView

   // Get the value of the text view.
   val countString = showCountTextView.text.toString()

   // Convert value to a number and increment it
   var count: Int = Integer.parseInt(countString)
   count++

   // Display the new value in the text view.
   showCountTextView.text = count.toString();
}
  1. The method is ready. What do you need to do to make the count button call this method when it is clicked? Go ahead and do it now.

    Hint: set the onClick property of the button.
  2. Run your app. Press the count button and watch the count update.

Kotlin Android Extensions Plugin

You have learned that you can get a View by using findViewById(). If you access View objects this way, you typically need to cast the result to the relevant subclass of View. To interact with views you will often need to use findViewById, so you'll be making these method calls a lot. In Kotlin, there's an even simpler way to write this code using the Kotlin Android Extensions plugin.

  1. Add the plugin to the build.gradle (Module:app) file. Note this is different than the build.gradle (Project: FirstAndroidApp).
  2. In In MainActivity.kt add the following import statement to the top:

import kotlinx.android.synthetic.main.activity_main.textView

  1. In MainActivity.kt go to the countMe method.
fun countMe (view: View) {

   // Get the value of the text view.
   val countString = textView.text.toString()

   // Convert value to a number and increment it
   var count: Int = Integer.parseInt(countString)
   count++

   // Display the new value in the text view.
   textView.text = count.toString();
}

The code val showCountTextView = findViewById(R.id.textView) as TextView is no longer needed. By importing kotlinx.android.synthetic.main.activity_main.textView you have access to textView.

In general, when you need a view from a layout file, you can import the following:

kotlinx.android.synthetic.main.<layout filename>.<id of view>

If you need all of the views from a layout file, you can use:

kotlinx.android.synthetic.main.<layout filename>.*

The name of this variable in the Kotlin code is from the id of the view. Here we see the imported TextView is called textView. This is because in the main_activity.xml code the id is textView:

So far, your app has a single screen. Now you will add a second activity that has its own screen.

You will update the Random button to display a second activity that shows a random number between 0 and the current count.

What you'll learn

Create a new activity

  1. Select the package name com.example.android.myfirstapp in apps > java > com.example.android.myfirstapp.

  2. Right click and select File > New > Activity > Empty Activity.
  3. In the "Configure Activity" wizard, change the activity name to SecondActivity. Make sure that the Source Language is Kotlin.

  1. Press Finish. Android Studio creates the Kotlin file and the XML layout file for the new activity.
  2. Wait for the gradle sync to finish in Android Studio.

    Gradle is the build system that Android Studio uses to compile and build the apps. You will see messages reporting the progress of the gradle build at the bottom of the screen.

Examine the manifest file

  1. Open the the Android manifest file by going to app > manifests > AndroidManifest.xml.



    The manifest file contains information about the app, including all the activities in the app.
  2. Examine the <activity> tag for the Main Activity:



    You see that the <activity> tag specifies the name of the activity. Main Activity is the activity that launches when the app opens, so it includes additional information that specifies it as the launcher activity.
  3. Examine the <activity> tag for the second activity. It simply specifies the activity name.



Examine the Kotlin file for the new activity

  1. Open SecondActivity.kt.
  2. Examine the onCreate() method. Notice the line that calls setContentView(). This method sets the layout of the new activity to activity_second.xml.
setContentView(R.layout.activity_second);


You will implement methods in this Activity to calculate and display a random number. First, though, you need to create the views in the layout to show the random number.

Create the layout for the new activity

The screen for the new activity will display a heading title and the random number. Here is what the screen will look like in the Design tab:

Add a TextView for the heading

  1. Open activity_second.xml. You see it has a ConstraintLayout that contains nothing. This is the default layout for activities created from the Empty Activity template.
  2. Add a TextView from the palette. This TextView will be used to display the heading at the top of the screen.
  3. Constrain the top edge of the TextView to the top of the screen, the left edge to the left of the screen, and the right edge to the right of the screen. Don't constrain the bottom edge.
  4. Set the width to match_parent, but set the height to wrap_content, so the height will change as needed to match the height of the content.
  5. Set the id to @+id/textview_label.
  6. Set top, left and right margins to 24dp. Left and right margins may also be referred to as "start" and "end" to support localization for right to left languages.
  7. Set the text color to @color/colorPrimaryDark and the text size to 24sp.
  8. Set the text to "Here is a random number between 0 and %1d."
  9. Extract the text into a string resource called random_heading.



Here is the XML code for the TextView that displays the heading:

<TextView
   android:id="@+id/textview_label"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:layout_marginLeft="24dp"
   android:layout_marginRight="24dp"
   android:layout_marginTop="24dp"
   android:text="@string/random_heading"
   android:textColor="@color/colorPrimaryDark"
   android:textSize="24sp"
   app:layout_constraintLeft_toLeftOf="parent"
   app:layout_constraintRight_toRightOf="parent"
   app:layout_constraintTop_toTopOf="parent"
   />

Add the TextView to display the random number

  1. Add a TextView to display the random number.
  2. Set both width and height to wrap_content.
  3. This new TextView will sit under the heading TextView. Constrain the top edge to the bottom of the heading TextView. Constrain each of the other edges to the corresponding edge of the screen.

  4. Set the id to @+id/textview_random.
  5. Set top, left and right margins to 24dp.
  6. Set the textColor to @android:color/white, set the textSize to 72sp, and the textStyle to bold.
  7. Set the text to R. This text is just a placeholder until the random number is generated.
  8. Set the layout_constraintVertical_bias to 0.45.

    This TextView is constrained on all edges, so it's better to use a vertical bias than margins to adjust the vertical position, to help the layout look good on different screen sizes and orientations.

Here is the XML code for the TextView that displays the random number:

<TextView
   android:id="@+id/textview_random"
   android:text="R"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:textColor="@android:color/white"
   android:textSize="72sp"
   android:textStyle="bold"
   app:layout_constraintTop_toBottomOf="@+id/textview_label"
   app:layout_constraintBottom_toBottomOf="parent"
   app:layout_constraintLeft_toLeftOf="parent"
   app:layout_constraintRight_toRightOf="parent"
   app:layout_constraintVertical_bias="0.45"
   />

Change the background color of the layout

Give your new activity a different background color than the first activity:

  1. In colors.xml, add a new color resource:
<color name="screenBackground2">#26C6DA</color>
  1. In the layout for the second activity, set the background of the ConstraintLayout to the new color.

    In Properties panel:




    Or in XML:
android:background="@color/screenBackground2"

Your app now has a completed layout for the second activity. You can view it in the Design panel, but if you run your app there is no way (yet) to switch to the second activity.

Start the second activity

Intents are messaging objects that abstractly represent the desire or intent to do some action. They are basically a message saying "I want action X to happen", where action X is something like starting an activity. Once this message is sent, it's up to the Android Framework to determine what the result of the intent will be. To start the second activity, you will need to create an Intent object for opening the activity. Then you will call startActivity() with that Intent, which sends that message to the Android framework. The Android Framework will then open an activity for you. You will do this now:

  1. Open the Kotlin code for the main activity, MainActivity.kt.
  2. Add a new method, randomMe(), that's invoked when the Random button is clicked.

    Quick, without looking it up, what are the requirements for a method that is invoked by clicking a View? If you can't remember, take a look at the toastMe() and countMe() methods.
  3. Add the code to start the second activity inside the randomMe() method:
// Create an Intent to start the second activity
val randomIntent = Intent(this, SecondActivity::class.java)

// Start the new activity.
startActivity(randomIntent)
  1. What else do you need to do to associate this method with the Random button? Do it now.
  2. Run the app. Click the Random button. The second activity appears, but it does not show a random number yet.



Pass information between activities

The goal of the second activity is to generate and display a random number between zero and the current value of count. Therefore the second activity needs to know the count. You can pass information to the second activity by putting extra information in the Intent, using the putExtra() method.

The second activity can get the Intent that started it, and then get the extra data from that Intent.

Update MainActivity to pass the extra data to the second activity

  1. In SecondActivity.kt, declare a static variable TOTAL_COUNT, to use as the key for the extra data.
companion object {
   const val TOTAL_COUNT = "total_count"
}
  1. Edit the randomMe() method. First get the current count by getting the value from the TextView that shows the count. Convert the count to an int, then use putExtra() on the Intent to add the count to the Intent. The putExtra() method takes a key and a value; specify the key as the TOTAL_COUNT constant from SecondActivity.kt.
randomIntent.putExtra(SecondActivity.TOTAL_COUNT, count)

Here is the complete code for the randomMe() method.

fun randomMe (view: View) {
   // Create an Intent to start the second activity
   val randomIntent = Intent(this, SecondActivity::class.java)

   // Get the current value of the text view.
   val countString = textView.text.toString()

   // Convert the count to an int
   val count = Integer.parseInt(countString)

   // Add the count to the extras for the Intent.
   randomIntent.putExtra(SecondActivity.TOTAL_COUNT, count)
  
   // Start the new activity.
   startActivity(randomIntent)
}

Update SecondActivity to compute and display a random number

You have written the code to send the current count to the second activity. The next step is to add code to SecondActivity.kt to retrieve and use the current count.

Write the method to retrieve the count and then compute and display the random number

  1. In SecondActivity.kt, Add a method, showRandomNumber() that takes no arguments.
  2. Define this method to generate and display a random number, where the max value is the count that was passed to the activity.
  3. Use getIntent() to get the intent that started this activity. Use getIntExtra() on the intent to get the value of the extra data; the arguments are the key and the default value if the key is not found.


Here is the complete code for showRandomNumber():

// Android extensions import statements for the two views to update
import kotlinx.android.synthetic.main.activity_second.textview_random
import kotlinx.android.synthetic.main.activity_second.textview_label

//Other class code...

fun showRandomNumber() {
   // Get the count from the intent extras
   val count = intent.getIntExtra(TOTAL_COUNT, 0)

   // Generate the random number
   val random = Random()
   var randomInt = 0
   // Add one because the bound is exclusive
   if (count > 0) {
       // Add one because the bound is exclusive
       randomInt = random.nextInt(count + 1)
   }

   // Display the random number.
   textview_random.text = Integer.toString(randomInt)

   // Substitute the max value into the string resource
   // for the heading, and update the heading
   textview_label.text = getString(R.string.random_heading, count)
}

Update onCreate()

When an Activity starts, its onCreate() method is called. Currently the onCreate() method for SecondActivity sets the layout for the activity. You will add a call to showRandomNumber() in onCreate() to update the layout to show the random number.

  1. Edit onCreate() in SecondActivity. As the final statement, call showRandomNumber().
override fun onCreate(savedInstanceState: Bundle?) {
   super.onCreate(savedInstanceState)
   setContentView(R.layout.activity_second)
   showRandomNumber()
}
  1. Run the app. Press the count button a few times, then press the Random button. Does the app display a random number in the new activity?

Congratulations, you have built your first Android app!

The intention of this codelab was to get you started building Android apps. We bet you want to know a lot more though, like how do I save data? How do I run background tasks? How do I ...

We encourage you to keep learning. We have in depth Java courses built by Google.

Written tutorials

Online courses

These interactive, video-based courses were created by Google experts in collaboration with Udacity. Take these course at your own pace in your own time.