Kotlin Android – AlertDialog

Android AlertDialog class is used to display a dialog box to alert the user with positive and negative buttons. Positive button is used to continue with the action specified. Negative button is used to dismiss the alerted action. You may provide your own custom code when positive or negative button is clicked.

AlertDialog appears on top of the activity layout. You may not physically access any other UI components of activity other that Alert Dialog box.

AlertDialog could be created only on UI thread.

Alert Dialog Box contains following three components.

  1. Title
  2. Message
  3. Buttons (that trigger Negative and Positive Actions)
Android Alert Dialog Example

To Create an AlertDialog, step by step process is

  1. Create an AlertDialog Builder using the activity’s context.
  2. Set message content using the builder.
  3. Set Positive Button Text and Action to be taken when the button is clicked using the builder.
  4. Set Negative Button Text and Action to be taken when the button is clicked using the builder.
  5. Create AlertDialog from the builder.
  6. You may set the title to the AlertDialog box using setTitle() method.

Note : All the setters (set methods) of AlertDialog.Builder return the modified AlertDialog.Builder and therefore supports chaining of methods. For example in a singe statement you can more than one setter.

ADVERTISEMENT

Example 1 – Android AlertDialog

In this Example Kotlin Android Application, we shall display an Alert Dialog if the user wants to close the application. If user clicks on Cancel button, the alert dialog is dismissed. If user clicks on Proceed button, the application is closed.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btnShowAlert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Alert"/>

</LinearLayout>

MainActivity.kt

package com.tutorialkart.alertdialogexample

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import android.app.AlertDialog
import android.content.DialogInterface

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // when button is clicked, show the alert
        btnShowAlert.setOnClickListener {
            // build alert dialog
            val dialogBuilder = AlertDialog.Builder(this)

            // set message of alert dialog
            dialogBuilder.setMessage("Do you want to close this application ?")
                    // if the dialog is cancelable
                    .setCancelable(false)
                    // positive button text and action
                    .setPositiveButton("Proceed", DialogInterface.OnClickListener {
                        dialog, id -> finish()
                    })
                    // negative button text and action
                    .setNegativeButton("Cancel", DialogInterface.OnClickListener {
                        dialog, id -> dialog.cancel()
                    })

            // create dialog box
            val alert = dialogBuilder.create()
            // set title for alert dialog box
            alert.setTitle("AlertDialogExample")
            // show alert dialog
            alert.show()
        }
    }
}

Run this Android Application in your Android phone or Emulator. You would get the following output on the screen, when you click on “Show Alert” button.

Android Alert Dialog Example

Download Complete Source Code of this Example Android Application

Conclusion

In this Kotlin Android TutorialAlertDialog Example, we have learnt to display an Alert Dialog box in Activity. We also learnt to set title, message and Positive, Negative buttons of AlertDialog.