Learn to create a simple Alert Dialog in Android using Kotlin

Creating a simple Alert Dialog in Android:

Alert Dialogs are used to take user decision before performing any operation. For example, we can show one Alert Dialog to the user to get a confirmation if the user is trying to delete something using our App. Normally, a dialog contains a title, content area and three action buttons.

The title is the title of the dialog. It is an optional value. The content area is the place to display the main layout. It can be a simple message, a list, a slider or any other custom layout. The action buttons are buttons to take user input. We can have at max 3 action buttons.

How to create Alert Dialog:

Toa create an alert dialog, we need to create one class as the container of the dialog. This class should extend the DialogFragment class and the main activity will use this class to handle the dialog like changing its appearance, handling the clicks on the buttons etc.

Let’s start writing code.

The first thing we need to create one file that will use as the DialogFragment. Create one file MyDialog.kt with the below code:

import android.app.Dialog
import android.content.DialogInterface
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import java.lang.IllegalStateException

class MyDialog : DialogFragment() {
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return activity?.let{
            val alertBuilder = AlertDialog.Builder(it)

            alertBuilder.setTitle("Are you sure ?")
            alertBuilder.setMessage("If you want to delete the file, please click on OK.")

            alertBuilder.setPositiveButton("OK", DialogInterface.OnClickListener{dialog, id ->
                Log.d("mydialoglog", "OK Pressed")
            }).setNegativeButton("Cancel", DialogInterface.OnClickListener{dialog, id ->
                Log.d("mydialoglog", "Cancel Pressed")
            }).setNeutralButton("Dismiss", DialogInterface.OnClickListener{dialog, id ->
                Log.d("mydialoglog", "Dismiss Pressed")
            })
            alertBuilder.create()
        } ?: throw IllegalStateException("Exception !! Activity is null !!")
    }
}

Here,

  • MyDialog is a class that is used to create a AlertDialog.
  • The first thing we are doing here is to create a builder for the AlertDialog using AlertDialog.Builder.
  • It is using builder design pattern. So, we can set the title, message,and buttons to this object.
  • The positive button is used to get some positive actions, the negative button is used to get some negative actions and the neutral button is used to get neutral actions like dismissing the alert dialog. For each of the button clicks, we are getting one callback and logging one message for each.
  • The final create() is used to create the Alert builder.

That’s it. Now we can use this class to show an alert. For example, below is the MainActivity.kt file:

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View

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

    fun showAlert(view: View) {
        MyDialog().show(supportFragmentManager, "mydialog")
    }
}

It calls the showAlert method on a button click. Below is the activity_main.xml file for this activity:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/alertButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="showAlert"
        android:text="Click Me"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

It will place a button at the center of the activity. Clicking on it, it will call the showAlert method, that will show the alert dialog using MyDialog class.

The dialog will look as like below: Android alertdialog example

You might also like: