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 the Java programming language. Kotlin is an officially supported language for developing Android apps, along with Java.
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 adept at reading code, you will likely be able to follow this codelab, even if you don't have much experience with Kotlin.
You write Android apps in Kotlin or in the Java programming language using an IDE called Android Studio. Based on JetBrains' IntelliJ IDEA software, Android Studio is an IDE designed specifically for Android development.
To work through this codelab, you will need a computer that can run Android Studio 3.6 or higher (or already has Android Studio 3.6 or higher installed).
You can download Android Studio 3.6 from the Android Studio page.
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 OpenJDK (Java Development Kit) is bundled with Android Studio.
The installation is similar for all platforms. Any differences are noted below.
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 an Android virtual or physical device.
Here's what the finished app will look like:
After these steps, Android Studio:
When your project first opens in Android Studio, there may be a lot of windows and panes open. To make it easier to get to know Android Studio, here are some suggestions on how to customize the layout.
At this point, your screen should look a bit less cluttered, similar to the screenshot shown below.
The upper left of the Android Studio window should look similar to the following diagram:
Based on you selecting the Basic Activity template for your project, Android Studio has set up a number of files for you. You can look at the hierarchy of the files for your app in multiple ways, one of which is in Project view (2). Project view shows your files and folders structured in a way that is convenient for working with an Android project. (This does not always match the file hierarchy! To see the file hierarchy, choose the Project files view by clicking (3).)
In the Project > Android view you see three or four top-level folders below your app folder: manifests, java, java (generated) and res. You may not see java (generated) right away.
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. activity_main.xml
. It also contains content_main.xml
, fragment_first.xml
, and fragment_second.xml
.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.
The AVD Manager now shows the virtual device you added.
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.
What you need:
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:
Now you can connect your device and run the app from Android Studio.
If you're stuck, quit Android Studio and restart it.
If Android Studio does not recognize your device, try the following:
If your computer still does not find the device or declares it "unauthorized":
If you are still having trouble, check that you installed the appropriate USB driver for your device. See the Using Hardware Devices documentation.
Check the troubleshooting section in the Android Studio documentation.
When you created the project and selected Basic Activity, Android Studio set up a number of files, folders, and also user interface elements for you, so you can start out with a working app and major components in place. This makes it easier to build your application.
Looking at your app on the emulator or your device, in addition to the Next button, notice the floating action button with an email icon. If you tap that button, you'll see it has been set up to briefly show a message at the bottom of the screen. This message space is called a snackbar, and it's one of several ways to notify users of your app with brief information.
At the top right of the screen, there's a menu with 3 vertical dots. If you tap on that, you'll see that Android Studio has also created an options menu with a Settings item. Choosing Settings doesn't do anything yet, but having it set up for you makes it easier to add user-configurable settings to your app.
Later in this codelab, you'll look at the Next button and modify the way it looks and what it does.
Generally, each screen in your Android app is associated with one or more fragments. The single screen displaying "Hello first fragment" is created by one fragment, called FirstFragment
. This was generated for you when you created your new project. Each visible fragment in an Android app has a layout that defines the user interface for the fragment. 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.
Every element in a layout is a view. In this task, you'll explore some of the panels in the layout editor, and you'll learn how to change properties of views.
fragment_first.xml
.The panels to the right of the Project view comprise the Layout Editor. They may be arranged differently in your version of Android Studio, but the function is the same.
On the left is a Palette of views you can add to your app.
Below that is a Component Tree showing the views currently in this file, and how they are arranged in relation to each other.
In the center is the Design editor, which shows a visual representation of what the contents of the file will look like when compiled into an Android app. You can view the visual representation, the XML code, or both.
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.
Depending on the size of your screen and your preference, you may wish to only show the Design view or the Blueprint view, instead of both.
On the right is the Attributes panel. You'll learn about that later.
fragment_first.xml
, look at the Component Tree. If it's not showing, switch the mode to Design instead of Split or Code.ConstraintLayout
view. ConstraintLayout
is one example of a view group.ConstraintLayout
contains a TextView
, called textview_first
and a Button
, called button_first
.<androidx.constraintlayout.widget.ConstraintLayout>
. The root element contains a <TextView>
element and a <Button>
element.<androidx.constraintlayout.widget.ConstraintLayout
... >
<TextView
... />
<Button
... />
</androidx.constraintlayout.widget.ConstraintLayout>
TextView
element.<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello first fragment"
... />
hello_first_fragment
.android:text="@string/hello_first_fragment"
values/strings.xml
opens with the string highlighted.
<string name="hello_first_fragment">Hello first fragment</string>
string
property to Hello World!
. fragment_first.xml
.textview_first
in the Component Tree.TextView
in Attributes, notice it still refers to the string resource @string/hello_first_fragment
. Having the strings in a resource file has several advantages. You can change the value of string without having to change any other code. This simplifies translating your app to other languages, because your translators don't have to know anything about the app code.textview_first
still selected in the Component Tree, in the layout editor, in the list of attributes, under Common Attributes, expand the textAppearance field. (You may need to scroll down to find it.)g
.TextView
. You see that the new properties have been added.<TextView
android:id="@+id/textview_first"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-condensed"
android:text="@string/hello_first_fragment"
android:textColor="@android:color/darker_gray"
android:textSize="30sp"
android:textStyle="bold"
TextView
.So far you have learned how to change property values. Next, you will learn how to create more resources like the string resources you worked with earlier. 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.
First, you'll learn how to add new color resources.
Change the text color and background of the TextView
<resources>
<color name="colorPrimary">#6200EE</color>
<color name="colorPrimaryDark">#3700B3</color>
<color name="colorAccent">#03DAC5</color>
</resources>
The colors.xml
file opens in the editor. So far, three colors have been defined. These are the colors you can see in your app layout (for example, purple for the app bar).
fragment_first.xml
so you can see the XML code for the layout.TextView
called android:background
, and start typing to set its value to @color
. You can add this property anywhere inside the TextView code.android:textColor
and give it a value of @android:color/white
. TextView
now has a dark blue or purple background, and the text is displayed in white.colors.xml
, create a new color resource called screenBackground:<color name="screenBackground">#FFEE58</color>
A Color can be defined as 3 hexadecimal numbers (#00-#FF, or 0-255) representing the red, blue, and green (RGB) components. The color you just added is yellow. Notice that the colors corresponding to the code are displayed in the left margin of the editor.
Note that a color can also be defined including an alpha value (#00-#FF), which represents the transparency (#00 = 0% = fully transparent, #FF = 100% = fully opaque). When included, the alpha value is the first of 4 hexadecimal numbers (ARGB).
The alpha value is a measure of transparency. For example, #88FFEE58 makes the color semi-transparent, and if you use #00FFEE58, it's fully transparent and disappears from the left-hand bar.
fragment_first.xml
. ConstraintLayout
.colors.xml
. Click the Custom tab to choose a custom color with an interactive color chooser.colorPrimary
and colorPrimaryDark
colors.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.
fragment_first.xml
, in the Component Tree, select the ConstraintLayout
.ConstraintLayout
is the root view of this Fragment
, so the "parent" layout size is effectively the size of your screen.textview_first
. Currently the layout width and height are wrap_content, which tells the view to be just big enough to enclose its content (plus padding)TextView
expands to match the ConstraintLayout
except for the button. The button and the text view are at the same level in the view hierarchy inside the constraint layout, so they share space.TextView
and the Button
back to wrap_content.In this task, you will add two more buttons to your user interface, and update the existing button, as shown below.
fragment_first.xml
, look at the constraint properties for the TextView
.app:layout_constraintBottom_toTopOf="@id/button_first"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
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.
textview_first
in the Component Tree and look at the Constraint Widget in the Attributes panel.TextView
to its parent, the ConstraintLayout
, or to the Next button for the bottom constraint.To learn how to use constraints to connect the positions of views to each other, you will add buttons to the layout. Your first goal is to add a button and some constraints, and change the constraints on the Next button.
TextView
near the other button.You will now constrain the top of the button to the bottom of the TextView
.
Button
.Button
onto the circle at the bottom of the TextView
.Button
moves up to sit just below the TextView
because the top of the button is now constrained to the bottom of the TextView
.Button
, including Top -> BottomOf textView.TextView
.app:layout_constraintTop_toBottomOf="@+id/textview_first"
Before adding another button, relabel this button so things are a little clearer about which button is which.
button
to toast_button
.You will adjust the button labeled Next, which Android Studio created for you when you created the project. The constraint between it and the TextView
looks a little different, a wavy line instead of a jagged one, with no arrow. This indicates a chain, where the constraints link two or more objects to each other, instead of just one to another. For now, you'll delete the chained constraints and replace them with regular constraints.
Ctrl
key (Command
on a Mac) and move the cursor over the circle for the constraint until the circle highlights, then click the circle.If you delete a constraint and want it back, either undo the action, or create a new constraint.
TextView
.TextView
, and then delete the constraint from the bottom of the text to the Next button.TextView
and the bottom is constrained to the bottom of the screen. The right side of the button is constrained to the right side of the screen.TextView
to the bottom of the screen.Your layout should now look something like this.
fragment_first.xml
layout file, find the text property for the toast_button
button.<Button
android:id="@+id/toast_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
"Button"
is directly in the layout field, instead of referencing a string resource as the TextView
does. This will make it harder to translate your app to other languages.toast_button_text
and the resource value to Toast
and click OK.android:text
property has changed to @string/toast_button_text
.<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/toast_button_text"
toast_button_text
.<resources>
...
<string name="toast_button_text">Toast</string>
</resources>
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.) And you know how to change the id of a view.
The Next button already has its text in a string resource, but you'll make some changes to the button to match its new role, which will be to generate and display a random number.
button_first
to random_button
in the Attributes panel.strings.xml
, right-click on the next
string resource.random_button_text
.Next
to Random
.random_button_text
to below toast_button_text
.Your final layout will have three buttons, vertically constrained the same, and evenly spaced from each other.
fragment_first.xml
, add another button to the layout, and drop it somewhere between the Toast button and the Random button, below the TextView
.TextView
; constrain the bottom of the third button to the bottom of the screen.Your layout should look something like this:
fragment_first.xml
. Do any of the buttons have the attribute app:layout_constraintVertical_bias
? It's OK if you do not see that constraint.Here is the XML code for the finished 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 your app.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/screenBackground"
tools:context=".FirstFragment">
<TextView
android:id="@+id/textview_first"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/colorPrimaryDark"
android:fontFamily="sans-serif-condensed"
android:text="@string/hello_first_fragment"
android:textColor="@android:color/white"
android:textSize="30sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/random_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/random_button_text"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textview_first" />
<Button
android:id="@+id/toast_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/toast_button_text"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textview_first" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/random_button"
app:layout_constraintStart_toEndOf="@+id/toast_button"
app:layout_constraintTop_toBottomOf="@+id/textview_first" />
</androidx.constraintlayout.widget.ConstraintLayout>
The next task is to make the buttons do something when they are pressed. First, you need to get the UI ready.
TextView
to show 0 (the number zero).id
of the last button you added, button2
, to count_button
in the Attributes panel in the design editor.count_button_text
and set the value to Count.
The buttons should now have the following text and ids:
Button | text | id |
Left button | Toast | @+id/toast_button |
Middle button | Count | @+id/count_button |
Right button | Random | @+id/random_button |
If you have these errors, fix them by updating the id
of the buttons in the constraints that are underlined in red.
app:layout_constraintEnd_toStartOf="@+id/random_button"
app:layout_constraintStart_toEndOf="@+id/toast_button"
Your app's layout is now basically complete, but its appearance can be improved with a few small changes.
colors.xml
, change the value of screenBackground
to #2196F3
, which is a blue shade in the Material Design palette. buttonBackground
. Use the value #BBDEFB
, which is a lighter shade in the blue palette.<color name="buttonBackground">#BBDEFB</color>
fragment_first.xml
or use the Attributes panel, whichever you prefer.)android:background="@color/buttonBackground"
24
in the field and press Enter.TextView
, either by clearing the value in the Attributes panel or by removing the android:background
attribute from the XML code. TextView
to 72sp.android:textSize="72sp"
TextView
to sans-serif
(if it's not already).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 view to see how the layout looks.)app:layout_constraintVertical_bias="0.3"
app:layout_constraintHorizontal_bias="0.5"
in XML).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. In this task, you will make your buttons respond when the user presses them.
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
.
To make your life easier, you can enable auto-imports so that Android Studio automatically imports any classes that are needed by the Kotlin code.
In this step, you will attach a Kotlin 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.
FirstFragment.kt
. (app > java > com.example.android.myfirstapp > FirstFragment).onCreateView()
and onViewCreated()
. These methods execute when the fragment starts.findViewByID()
method, your code can find the random_button
using its id, R.id.random_button
.onViewCreated()
. It sets up a click listener for the random_button
, which was originally created as the Next button.view.findViewById<Button>(R.id.random_button).setOnClickListener {
findNavController().navigate(R.id.action_FirstFragment_to_SecondFragment)
}
Here is what this code does:
findViewById()
method with the id of the desired view as an argument, then set a click listener on that view. toast_button
that creates and displays a toast. Here is the code:// find the toast_button by its ID and set a click listener
view.findViewById<Button>(R.id.toast_button).setOnClickListener {
// create a Toast with some text, to appear for a short time
val myToast = Toast.makeText(context, "Hello Toast!", Toast.LENGTH_SHORT)
// show the Toast
myToast.show()
}
You have learned that to make a view interactive you need to set up a click listener for the view that says what to do when the view (button) is clicked on. The click listener can either:
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.
fragment_first.xml
layout file, notice the id
for the TextView
:<TextView
android:id="@+id/textview_first"
FirstFragment.kt
, add a click listener for the count_button
below the other click listeners in onViewCreated()
. Because it has a little more work to do, have it call a new method, countMe()
.view.findViewById<Button>(R.id.count_button).setOnClickListener {
countMe(view)
}
FirstFragment
class, add the method countMe(),
which takes a single View
argument. This method is invoked when the Count button is clicked and the click listener called. private fun countMe(view: View) {
}
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, textview_first
. ...
// Get the text view
val showCountTextView = view.findViewById<TextView>(R.id.textview_first)
showCountTextView
. ...
// Get the value of the text view.
val countString = showCountTextView.text.toString()
...
// Convert value to a number and increment it
var count = countString.toInt()
count++
TextView
by programmatically setting the text
property of the TextView
. ...
// Display the new value in the text view.
showCountTextView.text = count.toString()
Here is the whole method:
private fun countMe(view: View) {
// Get the text view
val showCountTextView = view.findViewById<TextView>(R.id.textview_first)
// Get the value of the text view.
val countString = showCountTextView.text.toString()
// Convert value to a number and increment it
var count = countString.toInt()
count++
// Display the new value in the text view.
showCountTextView.text = count.toString()
}
So far, you've focused on the first screen of your app. Next, you will update the Random button to display a random number between 0 and the current count on a second screen.
The screen for the new fragment will display a heading title and the random number. Here is what the screen will look like in the design view:
The %d indicates that part of the string will be replaced with a number. The R is just a placeholder.
fragment_second.xml
(app > res > layout > fragment_second.xml) and switch to Design view if needed. Notice that it has a ConstraintLayout
that contains a TextView
and a Button
.TextView
and the Button
.TextView
from the palette and drop it near the middle of the screen. This TextView
will be used to display a random number between 0 and the current count from the first Fragment
.id
to @+id/textview_random
(textview_random
in the Attributes panel.)TextView
to the bottom of the first TextView
, the left edge to the left of the screen, and the right edge to the right of the screen, and the bottom to the top of the Previous button.R
". This text is just a placeholder until the random number is generated.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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="R"
android:textColor="@android:color/white"
android:textSize="72sp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="@+id/button_second"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textview_second"
app:layout_constraintVertical_bias="0.45" />
fragment_second.xml
, select textview_second
, which currently has the text "Hello second fragment. Arg: %1$s"
in the hello_second_fragment
string resource.android:text
isn't set, set it to the hello_second_fragment
string resource.android:text="@string/hello_second_fragment"
id
to textview_header
in the Attributes panel.24dp
. Left and right margins may also be referred to as "start" and "end" to support localization for right to left languages.@color/colorPrimaryDark
and the text size to 24sp
. strings.xml
, change hello_second_fragment
to "Here is a random number between 0 and %d.
"hello_second_fragment
to random_heading
.Here is the XML code for the TextView
that displays the heading:
<TextView
android:id="@+id/textview_header"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginLeft="24dp"
android:layout_marginTop="24dp"
android:layout_marginEnd="24dp"
android:layout_marginRight="24dp"
android:text="@string/random_heading"
android:textColor="@color/colorPrimaryDark"
android:textSize="24sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
Give your new activity a different background color than the first activity:
colors.xml
, add a new color resource:<color name="screenBackground2">#26C6DA</color>
fragment_second.xml
, set the background of the ConstraintLayout
to the new color.android:background="@color/screenBackground2"
Your app now has a completed layout for the second fragment. But if you run your app and press the Random button, it may crash. The click handler that Android Studio set up for that button needs some changes. In the next task, you will explore and fix this error.
When you created your project, you chose Basic Activity as the template for the new project. When Android Studio uses the Basic Activity template for a new project, it sets up two fragments, and a navigation graph to connect the two. It also sets up a button to go from the first fragment to the second. This is the button you changed into the Random button. And now you want to send a number when the button is pressed.
nav_graph.xml
(app > res > navigation > nav_graph.xml).A screen similar to the Layout Editor in Design view appears. It shows the two fragments with some arrows between them. You can zoom with + and - buttons in the lower right, as you did with the Layout Editor.
SecondFragment
to the left, drag FirstFragment
to the left of SecondFragment
so they appear in the order you work with them.This will enable SafeArgs in Android Studio.
dependencies
section In the buildscript
section, and add the following lines after the other classpath
entries:def nav_version = "2.3.0-alpha02"
classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version"
apply plugin: 'androidx.navigation.safeargs.kotlin'
After a few moments, Android Studio should display a message in the Sync tab that it was successful:
FirstFragmentDirections
.FirstFragment
, and look at the Attributes panel to the right. (If the panel isn't showing, click on the vertical Attributes label to the right.)SecondFragment
.SecondFragment
, and look at the Attributes panel.The Arguments section shows nothing.
myArg
for the name and set the type to Integer, then click the Add button.The Next/Random button was set up by Android Studio to go from the first fragment to the second, but it doesn't send any information. In this step you'll change it to send a number for the current count. You will get the current count from the text view that displays it, and pass that to the second fragment.
FirstFragment.kt
(app > java > com.example.myfirstapp > FirstFragment)onViewCreated()
and notice the code that sets up the click listener to go from the first fragment to the second.textview_first
.val showCountTextView = view.findViewById<TextView>(R.id.textview_first)
Int
.val currentCount = showCountTextView.text.toString().toInt()
currentCount
as the argument to actionFirstFragmentToSecondFragment()
.val action = FirstFragmentDirections.actionFirstFragmentToSecondFragment(currentCount)
findNavController().navigate(action)
Here is the whole method, including the code you added earlier:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<Button>(R.id.random_button).setOnClickListener {
val showCountTextView = view.findViewById<TextView>(R.id.textview_first)
val currentCount = showCountTextView.text.toString().toInt()
val action = FirstFragmentDirections.actionFirstFragmentToSecondFragment(currentCount)
findNavController().navigate(action)
}
// find the toast_button by its ID
view.findViewById<Button>(R.id.toast_button).setOnClickListener {
// create a Toast with some text, to appear for a short time
val myToast = Toast.makeText(context, "Hello Toast!", Toast.LENGTH_SHORT)
// show the Toast
myToast.show()
}
view.findViewById<Button>(R.id.count_button).setOnClickListener {
countMe(view)
}
}
You have written the code to send the current count to the second fragment. The next step is to add code to SecondFragment.kt
to retrieve and use the current count.
SecondFragment.kt
, add an import for navArgs to the list of imported libraries.import androidx.navigation.fragment.navArgs
SecondFragment.kt
, before onViewCreated()
, add a line to define where the arguments are.val args: SecondFragmentArgs by navArgs()
SecondFragment.kt
below where the click listener is created, add lines to get the count argument, get the string and format it with the count, and then set it for textview_header
.val count = args.myArg
val countText = getString(R.string.random_heading, count)
view.findViewById<TextView>(R.id.textview_header).text = countText
val random = java.util.Random()
var randomNumber = 0
if (count > 0) {
randomNumber = random.nextInt(count + 1)
}
textview_random
.view.findViewById<TextView>(R.id.textview_random).text = randomNumber.toString()
Here is the whole method.
val args: SecondFragmentArgs by navArgs()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<Button>(R.id.button_second).setOnClickListener {
findNavController().navigate(R.id.action_SecondFragment_to_FirstFragment)
}
val count = args.myArg
val countText = getString(R.string.random_heading, count)
view.findViewById<TextView>(R.id.textview_header).text = countText
val random = java.util.Random()
var randomNumber = 0
if (count > 0) {
randomNumber = random.nextInt(count + 1)
}
view.findViewById<TextView>(R.id.textview_random).text = randomNumber.toString()
}
Congratulations, you have built your first Android app!
The intention of this codelab was to get you started building Android apps. We hope you want to know a lot more though, like how do I save data? How do I run background tasks? How do I display a list of photos? How do I ...
We encourage you to keep learning. We have more Android in Kotlin courses built by Google to help you on your learning journey
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.