Reading Time: 6 minutes

Dialogs are present in our every day lives in the digital world, almost every user knows what are we talking about when referring to dialogs: ‘those annoying small windows that cover the screen and interrupt what you want to do’… well sort of, it is like most of our Android UI tools, a way to communicate important messages with users. That’s why I have created this Android Alert Dialogs in Kotlin Tutorial.

This is Part 1 of this tutorial, if you want to have a look at the second part, go here:

First, take a look at the Android official definition of dialogs we find the following:

A dialog is a small window that prompts the user to make a decision or enter additional information. A dialog does not fill the screen and is normally used for modal events that require users to take an action before they can proceed.

https://developer.android.com/guide/topics/ui/dialogs

As an Android developer, you will use dialogs in most of your apps, think of examples on the apps you use every day. Here are three simple examples that come to my mind.

  1. Confirmation messages
  2. Alerts to input a date or text
  3. Alerts to pick an option.

Android Kotlin Alert Dialogs Tutorial

As you may already know, in this tutorial, we will learn how to create an Android dialog, although this is a beginner tutorial, anyone can follow along to brush on the basics and know the best practices. Start by creating a new Android Studio Project, if you don’t know how to do this go check my tutorial on it here, for the purpose of this tutorial I am using:

  • Android Studio 3.5.3
  • Kotlin 1.3
  • Compat Library: AndroidX

Starting the project

Start with an ’empty activity template’ and configure the default settings as shown in Image 1 below or if you prefer, here is the starter project I used for you to follow along:

Image1. Project settings to start

Run the app and you should be able to see something similar to Image 2, colors may vary.

Image2. Initial screen

Create a button to show the alert

The first thing you need to do on this screen is to replace the “Hello World” text from the screen and switch it for a button. This button will trigger our most basic alert. To do that head to activity_main.xml, the file should have been opened when you created the project, otherwise, look for it in the folder app > res > drawable. The first time you open the file you will see at the bottom left two tabs, Design, and Text, most likely the one selected is ‘Design’ (Image 3), although this is a good screen for previewing, almost always you will be editing your code in the ‘Text’ section.

Image 3. XML ‘design’ visual editor
Image 4. XML ‘text’ code editor

The lines that represent the “Hello world” text are in the <TextView> tag, in the image above (Image 4), they represent lines 9 to 16. Replace that code with the following:

<Button
    android:layout_width ="wrap_content"
    android:layout_height ="wrap_content"
    android:text ="Show basic dialog!"
    app:layout_constraintBottom_toBottomOf ="parent"
    app:layout_constraintLeft_toLeftOf ="parent"
    app:layout_constraintRight_toRightOf ="parent"
    app:layout_constraintTop_toTopOf ="parent" />

If you compare the code we had before in Image 4 and the new code you will notice we only changed the text and the name of the tag which before was “TextView” and now it is “Button”. As you can see Android XML layout code is pretty straightforward, the rest of the lines in there, that we didn’t modify are properties of the view that indicate it where to position in space, don’t worry about what they mean right now. Going back to the design tab you will now be able to get a preview of the button like shown in the image below (Image 5).

Image 5. Design preview

Now run the app and you should see the button on the screen, which by the way is similar to the preview. If you want to know how your result should look like, take a look at Image 6 below.

Image 6. Screen with the show dialog button.

Coding the Kotlin Code for the Alert Dialog

Open MainActivity.kt, this is the code that contains all the Kotlin code for controlling the screen we previously edited. If you didn’t have the file open since the creation of the project, you can find it in app > java > your project name > MainActivity.kt. As you may see this file has a small amount of code:

  1. The name of the package it belongs to.
  2. Some default imports.
  3. Your main activity class.
  4. The onCreate() function, which is a function that is executed, just after the screen is ‘created’. Inside of it, through the setContentView(R.layout.activity_main), instruction, you are telling the app to use the file activity_main.xml as the layout for this code.

Enough with the explanation, let’s get to the code!

Import the needed classes

First of all, in the imports line, add the following code:

import androidx.appcompat.app.AlertDialog
import android.view.View

The imports may be minimized, you can know this by a … signal after the word import. Open it, either by double-clicking these ellipses or by a (very small) ‘+’ icon to the right of the line. Don’t worry about the order, it doesn’t make any difference.

Create a method to show the Alert

Now for the alert itself, below the onCreate() method, create a new method to show the alert with this code:

fun showBasicDialog(view: View?) {
    //1
    val builder = AlertDialog.Builder(this)
    //2
    builder.setTitle("Alert")
    builder.setMessage("The body of my alert")
    //3
    builder.show()
}

Let’s go through this code part by part. I labeled the parts with comments (which you don’t have to include in your project), to ease the explanation:

  1. Android provides a default “builder” to create Alert Dialogs, so you don’t have to worry about the logic behind. Use it and tell the app to create a builder on ‘this’ class.
  2. You set the title and the message for your alert.
  3. You request the builder to show the alert.

Now we need to somehow call this method, at the bottom of the onCreate() add this line of code:

showBasicDialog(null)

If you are a bit confused about how your code should look now, take a look at the image below (Image 7) for clarification. Don’t worry, it’s a lot of new info and coding goes hand by hand with practicing.

Image 7. Main Activity Kotlin code

Now run the app and see what happens.

Image 8. Alert displaying

What happened? The app runs, but… the Alert showed just as the screen launched, can you identify why did this happen? Because of the line we added in the last step to the onCreate() method the Alert is showing right away, this isn’t what we want to do, but at least we know our alert works now.

Attaching the showAlert() method to the button action

The next step would be to make the button trigger the alert, instead of letting the onCreate() do the job. For this, go back to your activity_main.xml file and add the following line inside the button tag:

android:onClick = "showBasicDialog"

The result of the XML file is shown in the image below (Image 9).

Image 9. activity_main.xml code

It is important for you to notice something, the parameter added to the onClick property, has the same value as the name of the function we created above “fun showBasicDialog(view: View?)“, the key here is the ‘view’ parameter, the method you use on an onClick, has to have a view parameter in order to work.

Now delete the “showBasicDialog(null)” call from the onCreate, and run the app.

Image 10. Alert showing on button click

Did it work? Great! I hope everything has been easily understood and this Android Alert Dialogs Kotlin Tutorial was useful to you. If you want to see the result of this tutorial, you can download the item below:

If you liked the content on this post, please follow me at the bottom of the page. You can also buy me a coffee to support me!

Until next time!

Evana Margain Puig

(Visited 41 times, 2 visits today)