Building Cloud Expertise with centron - Our Tutorials

Whether you are a beginner or an experienced professional, our practical tutorials provide you with the knowledge you need to make the most of our cloud services.

Compact Tutorial: Creating Android Alert Dialogs with Kotlin

Discover in this hands-on tutorial how to create alert dialogs in your Android app using Kotlin. From the basics to customizing buttons and styles – learn everything step by step. An essential guide for developers to create interactive user experiences.

What are Alert Dialogs?

An alert dialog is a window that appears on the screen. They usually display information and prompt a user action. An alert dialog consists of three core components:

  • Title text
  • Message text
  • Buttons – There are three types of buttons: Positive, Negative, and Neutral

To create an AlertDialog, we use the inner class AlertDialog.Builder.

 
val alertDialogBuilder = AlertDialog.Builder(this)

We pass the context in the constructor. Optionally, we can pass another parameter, the alert dialog style.

Methods of Alert Dialogs

Some of the methods that can be used on an AlertDialog:

  • setTitle
  • setMessage
  • setIcon
  • setCustomTitle – Here you can pass a custom view to be placed instead of the title in the alert dialog.
  • setPositiveButton – Here we pass the string name along with the method for the button click callback.
  • setView – Used to add a custom view to the alert dialog.
  • setList – Used to set an array of strings to be displayed in the form of a list.
  • setMultiChoiceList – Again, we can set an array, but this time we can select multiple items thanks to CheckBox.
  • setPositiveButtonIcon – Sets an icon next to the button.
  • show() – Used to display the AlertDialog.
  • setDismissListener – Here you can set the logic to be triggered when the AlertDialog is dismissed.
  • setShowListener – Sets the logic to be triggered when the AlertDialog is shown.
  • setCancelable – Requires a boolean value. By default, all alert dialogs are cancelable when clicking the button or touching outside. If this method is set to false, you need to explicitly cancel the dialog with the dialog.cancel() method.

Kotlin Code for Alert Dialogs

To use AlertDialog in your Android Studio project, import the following class.

 import android.support.v7.app.AlertDialog;

The following Kotlin code is used to create a simple alert dialog.

 val builder = AlertDialog.Builder(this)
builder.setTitle("Androidly Alert")
builder.setMessage("We have a message")

builder.setPositiveButton(android.R.string.yes) { dialog, which ->
    Toast.makeText(applicationContext,
            android.R.string.yes, Toast.LENGTH_SHORT).show()
}

builder.setNegativeButton(android.R.string.no) { dialog, which ->
    Toast.makeText(applicationContext,
            android.R.string.no, Toast.LENGTH_SHORT).show()
}

builder.setNeutralButton("Maybe") { dialog, which ->
    Toast.makeText(applicationContext,
            "Maybe", Toast.LENGTH_SHORT).show()
}

builder.show()

The builder.show() displays the alert dialog on the screen. Within the setPositiveButton function, we pass the button text along with a Kotlin function that is triggered when this button is clicked. The function is part of the DialogInterface.OnClickListener() interface. The function type is (DialogInterface, Int) -> Unit. DialogInterface is an instance of the dialog, and Int is the ID of the clicked button. In the above code, we have represented this function as a higher-order Kotlin function. The dialog and which represent the two arguments. We can enhance the function by passing _ if the arguments are not used. The functions would look like this:

 builder.setPositiveButton(android.R.string.yes) { _,_ ->
    Toast.makeText(applicationContext,
            android.R.string.yes, Toast.LENGTH_SHORT).show()
}

Alternatively, we can also display the dialog using the instance of the AlertDialog class. Replace builder.show() with:

 val alertDialog = builder.create()
alertDialog.show()

Instead of defining the functions for clicking the buttons separately, we can also define higher-order functions separately.

 val positiveButtonClick = { dialog: DialogInterface, which: Int ->
    Toast.makeText(applicationContext,
            android.R.string.no, Toast.LENGTH_SHORT).show()
}

Now, set this val property into the setPositiveButton Kotlin function as follows:

 builder.setPositiveButton("OK", DialogInterface.OnClickListener(function = positiveButtonClick))
//or
builder.setPositiveButton(android.R.string.yes, positiveButtonClick)

The latter makes the code much more concise. Below is a screenshot from our activity class with the above applied function for each of the buttons. You can pass null instead of the function if you don’t want to maintain any action when clicking the button.

Kotlin still has more ways to improve the readability of the above code.

Unlock Advanced Features with Our Free Trial!

Ready to enhance your Android app development with powerful alert dialogs? Sign up for our free trial today and experience the full range of features our cloud services offer. Start building more interactive and user-friendly apps with ease. Don’t miss out – join us now and take your development skills to the next level!

Try for free!