Tutorials  /  JavaScript

Compact Tutorial: Creating Android Alert Dialogs with Kotlin

Ccentron Redaktion · June 2024 ·4 min read ·JavaScript, Tutorial

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.

Code
val alertDialogBuilder = AlertDialog.Builder(this)

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

VM

Matching infrastructure at centron

Node applications need somewhere to run: ccloud³ VMs with full root access from €3.12 per month – or as a managed server if you would rather not run it yourself. Rent a cloud server →

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.

Python
import android.support.v7.app.AlertDialog;

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

Code
 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:

Code
 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:

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

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

Code
 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:

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

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie JavaScript
Teilen
Noch offene Fragen?

Unser Team hilft Ihnen bei Ihrem konkreten Setup weiter – von Menschen, die die Plattform selbst betreiben.

War dieses Tutorial hilfreich?

Ihre Antwort wird anonym gespeichert und hilft uns, die Tutorials zu verbessern.

Kommentare

Noch keine Kommentare – stellen Sie die erste Frage zu diesem Tutorial.

Zum Kommentieren anmelden

Kommentare stehen centron-Kunden offen. Melden Sie sich in Ihrem Konto an, um eine Frage zu diesem Tutorial zu stellen.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren