In this codelab, you'll learn how to build and run your first Android app in the Kotlin programming language. (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 must know already

This codelab is written for programmers and assumes that you know either the Java or Kotlin programming language. 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.

What you'll learn

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).

Android Studio provides a complete IDE, including an advanced code editor and app templates. It also contains tools for development, debugging, testing, and performance that make it faster and easier to develop apps. You can use Android Studio to test your apps with a large range of preconfigured emulators, or on your own mobile device. You can also build production apps and publish apps on the Google Play store.

Android Studio is available for computers running Windows or Linux, and for Macs running macOS. The newest OpenJDK (Java Development Kit) is bundled with Android Studio.

The installation is similar for all platforms. Any differences are noted below.

  1. Navigate to the Android Studio download page and follow the instructions to download and install Android Studio.
  2. Accept the default configurations for all steps, and ensure that all components are selected for installation.
  3. After the install is complete, the setup wizard downloads and installs additional components, including the Android SDK. Be patient, because this process might take some time, depending on your internet speed.
  4. When the installation completes, Android Studio starts, and you are ready to create your first project.

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. Select Empty Activity. Click Next.
  4. Give your application a name such as My First App.
  5. Set the Language to Kotlin.
  6. Leave the defaults for the other fields.
  7. 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. If you click Project (2), you can hide or show the Project view. You might need to select View > Tool Windows 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 four top-level folders below your app folder: manifests, java, java (generated) 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 language files are organized here. The java folder contains three subfolders:

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

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

    com.example.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 (or 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 > 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 pre-configured hardware device definitions.
  3. Choose a device definition, such as Pixel 2, and click Next. (It really doesn't matter which device definition you pick).
  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 your new 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.


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 class known as an activity. The single screen with "Hello World" displayed is created by one activity, called MainActivity. 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 (app > res > layout).

  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. 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 menu 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 Editor.

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

  ... >

      ...  />


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 soon.

   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 Attributes panel on the right.

  1. In the text field of the TextView in the Attributes 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 in the list of attributes, expand the textAppearance field for the TextView. (You may need to scroll down to find it.)

  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 attributes

  1. Return to the Design tab. If you don't see any attributes, make sure the TextView is still selected in the Component Tree. Scroll down until you find All Attributes.

  2. Scroll through the list to get an idea of the attributes 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 res > values > 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 Attributes panel if it's cluttering your view.

    You see that the TextView now has a dark green 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 Attributes panel, 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. Click the yellow patch to the left of the color value in the background field.

    It shows a list of 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 the 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 Attributes panel, show the minimized view of the attributes. Find and expand the Layout section.

    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_constraint.

    The width and height show 0dp, and the text moves to the upper left, while the TextView expands to match the ConstraintLayout.

  3. Explore what happens if the width is match_constraint 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 Widget in the Attributes panel.

    Each of the grey dots represents a constraint from the TextView to its parent, the ConstraintLayout.
  3. Notice that the blueprint and design views also shows the constraints when a particular view is selected.

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 if you need to, so that you can see many of the items in the palette.

  2. Click on some of the categories, and scroll the listed items if needed 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 Widget in the Attributes panel. It shows some constraints for the Button, including Top -> BottomOf textView.
  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.

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.
  1. 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"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android=""

       app:layout_constraintTop_toTopOf="parent" />

       app:layout_constraintTop_toBottomOf="@+id/textView" />

       app:layout_constraintTop_toBottomOf="@+id/textView" />

       app:layout_constraintTop_toBottomOf="@+id/textView" />


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 Attributes panel in the design editor. Set the text and id as shown here:




Left button



Middle button



Right 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.

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 Attributes panel, whichever you prefer.)

Change the margins of the left and right buttons

  1. Give the Toast button a left (start) margin of 24dp and give the Random button a right (end) margin of 24dp. (Using start and end instead of left and right makes these margins work for all language directions.)

Update the appearance of the TextView

  1. Remove the background color of the TextView, either by clearing the value in the Attributes 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.
  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.)

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 by going to File > Other Settings > Preferences for New Projects.
  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 the button. A toast is a short message that appears briefly at the bottom of the screen.

  1. Open MainActivity.kt. (Expand app > java > 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.
  1. Add a new method called toastMe() to the MainActivity class. The toastMe() method takes a single argument of type 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)
  1. In the Text tab for the layout file, add an android:onClick property to the Toast button. Set the value to 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. In the next step, you 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:
  1. In MainActivity.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<TextView>(
  1. Get the value of the showCountTextView.
fun countMe (view: View) {
   // Get the text view
   val showCountTextView = findViewById<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<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)
  1. Display the new value in the TextView.
fun countMe (view: View) {
   // Get the text view
   val showCountTextView = findViewById<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)

   // 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.

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.myfirstapp in apps > java > com.example.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 set to 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 MainActivity:

    You see that the <activity> tag specifies the name of the activity. MainActivity 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.

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_constraint, 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:


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. Left and right margins may also be referred to as "start" and "end" to support localization for right to left languages.
  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:


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 the Attributes panel:

    Or in XML:

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,

// Start the new activity.
  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 constant TOTAL_COUNT, to use as the key for the extra data.
companion object {
    const val TOTAL_COUNT = "total_count"
  1. In MainActivity.kt, 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 integer, 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,

   // Get the text view
   val textView = findViewById<TextView>(
   // 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.

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(): (you will need to import java.util.Random)

import java.util.Random

// rest of class definition

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.
   findViewById<TextView>( = Integer.toString(randomInt)

   // Substitute the max value into the string resource
   // for the heading, and update the heading
   findViewById<TextView>( = 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?) {
  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 Kotlin and 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 courses at your own pace in your own time.