Your First Kotlin Android App: An App From Scratch
Part 2: Work with an Android Activity Handle Interactions
— Android & Kotlin

Lesson Complete

Play Next Lesson
Next

Handle Interactions

This video was last updated on Jul 5 2022

Handle events triggered when users interact with your app. An Alert Dialog will display when the “Hit me” button is clicked.

Contributors

At this stage, you’ve added the hit me button to bull’s eye but when you tap it, nothing happens. That’s not really how a button should work, right? you need to give some feedback to the user. Let’s start by making the button print out a test message when you tap it.

To add a click interaction you need to set up a click listener. Enter the following code inside the onCreate method of the activity:

binding.hitMeButton.setOnClickListener({
    Log.i("Button Click Event", "You clicked the Hit Me Button")
})

The above code is the syntax for setting up a click listener. Ignore the warning by Android Studio for now. This listener as its name suggests, listens for click events on a button. So it will execute some code when the button is clicked. For instance you can navigate to a different page or show some dialog or even sign in a user if it’s a login screen.

Let’s break the code down. First, you get the button object from the binding instance. Then you call the setOnClickListener function using the dot notation and pass in a function as its argument This function will be executed when the button is clicked.

We talked about functions earlier and how functions can accept arguments. That is what this function does, it accepts a function as an arguemnt that will execute an action. In this case the action we want to take is to print a message.

For this you use the Log class and call the i function. The i function here stands for information. The Log class has different types of message channels and info is one of them. The Log class prints the message to the Logcat window. And you can use Log messages in combination with the Logcat window to debug our apps. The Logcat window comes with more features than basic print statements.

Now back to the info function. The first argument is the TAG. This is the message identifier. Normally, when working in larger apps, you use the class name where the log message is printed. But for now you just passed a simple string “Button Click Event.” The second argument is the message you want to print out.

Run your app. Then open up the Logcat window from the button group above the status bar below. You can see it logging different messages about processes that takes place in your app.

Go ahead and click on the hit me button. In the logcat window, verbose option is selected. Go ahead and click on it. You can see a list of different filtering options the Log class provides. Select the Info option.

Next beside that dropdown, you search for the tag. In this case i’ll just enter “Button” And you can see the log message. Click on the button once again. And you can see the message prints to the logcat window.

You can also see this message inside the run window. But the logcat window gives us more features just like the search feature when using log statements. Go ahead and close the logcat window.

One last thing. I know you might be wondering why we have this warning around the click listenter, right? Well, whenever a function accepts another function known as a lambda as an argument, android studio suggests you remove the parenthesis around the lambda argument.

I’ll go ahead and click on the start of the perenthesis then click on the bulb icon. And select “Move lambda argument out of parenthesis.” This fixes this warning and now you have cleaner code.

You’ll be seeing this type of syntax in the android codebase so it’s good to start getting used to it. And not to worry, you’ll be learning more about lambdas further down the learning path.

Now, this is a click interaction but in a real world app, you would want to do something more meaningful. Let’s display an alert dialog when the user clicks the button.

Enter the following code below onCreate() in main activity:

private fun showResult() {
    val dialogTitle = getString(R.string.result_dialog_title)
    val dialogMessage = getString(R.string.result_dialog_message)

    val builder = AlertDialog.Builder(this)

    builder.setTitle(dialogTitle)
    builder.setMessage(dialogMessage)
    builder.setPositiveButton(R.string.result_dialog_button_text) { dialog, _ ->
        dialog.dismiss()
    }

    builder.create().show()
}

You just created a function called showResult. The private access modifier keyword was added to it because we dont want this function to be accessed outside this class. A keyword in kotlin is just a reserved word that is used by kotlin. So for instance, you cannot create a variable named private or fun because fun is a reserved word and you can see them styled with a different color.

Inside it, you created two variables named dialogTitle and dialogMessage. These variables store the strings for title and message on the dialog. You get these values from the strings.xml file using the getString() function. You access these strings in this file from our activity using the R class.

The R class is generated when your app is compiled. It creates numeric constants that allow you to get the contents inside the res folder. These are things like ids of views, strings and even layouts. Note: Constants here simply mean variables whose values that cant be changed once they are assigned. So R.string.result_dialog_title behind the scenes is actually a numeric constant generated by the R class. The android tool generates a number but we just identify them with a descriptive name.

The strings for the dialog have been added to the starter project for this episode. To see them, hold down the command key and click on one of them. This takes you to the file where it was declared. And you can see the new strings that was added below. Okay, head back to the activity file.

Next, you declared an alert dialog builder which builds the alert dialog. And passed in this as the context argument. Context in Android is the background information of the activity and the application depending on how it is used.

In here, the context it requires is the that of the parent. So you pass in this which refers to the activity that contains the alert dialog and that’s the main activity. You’re simply passing in the background information of the activity to the alert dialog builder so it shows it properly on the screen.

In this case, it would build it inside the main acitvity with the correct design otherwise known as theme.

Then you use this builder instance to set the title and message of the of the dialog and pass in the variables we declared earlier. You then added the positive button to the dialog. Then passed in the text to display and the function otherwise known as the lambda that will be executed when the button is pressed. In here, you just dismiss the dialog. Note, you have access to the dialog in here because the click listener of the button supplies it.

Finally, you call the code to create and show the dialog.

Go ahead and restart the activity. We have an error. The activity restart failed.

In the run window, you can see it says “Interfaces changed or reordered.” This is because the alert dialog needs context information from the activity to work properly And simply restarting the activity wont do the trick here.

So go ahead and run the app to reinstall it.

Then click on the hit me button. And it doesnt work. This is because you havent called this new method you created inside the onCLickListener of the hit me button. Let’s do that now:

...
showResult()

You can see the color of the method definition changes because it is now used somewhere in our file.

Run your app once again. Then click on the hit me button.

Cool!!! A nice alert dialog is displayed with a title, message and a button. And clicking on the button dismisses the dialog.

Reviews

Comments