Open In App

How to Close Alert Dialog Box in Android Programmatically?

Last Updated : 13 Jan, 2022
Like Article

AlertDialog is a flash or an alert message with options that let the user proceed or deny any process or action. AlertDialog generally consists of the main title, the message, and two buttons, technically termed as a positive button and a negative button. Both positive and negative buttons can be programmed to perform various actions. By default, the negative button lets close the AlertDialog without any additional lines of code. However, in the case of a positive button, it is necessary to write code to perform any action even for closing the AlertDialog.

So through this article, we will show you how you could close an AlertDialog programmatically through the positive button. Follow the below procedures once the IDE is ready.

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.

Step 2: Working with the activity_main.xml file

No changes are to be made to the layout file, so we kept it untouched or default.


<?xml version="1.0" encoding="utf-8"?>
        android:text="Hello World!"
        app:layout_constraintTop_toTopOf="parent" />

Step 3: Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.


package org.geeksforgeeks.programmaticallyclosealertdialog
import android.os.Bundle
import android.widget.Toast
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        // Declaring and initializing 
        // a Builder for the Alert Dialog
        val mBuilder = AlertDialog.Builder(this)
            .setPositiveButton("Positive", null)
            .setNegativeButton("Negative", null)
        val mAlertDialog = mBuilder.create()
        // Changing Positive Button properties
        // such that something happens on click
        val mPositiveButton = mAlertDialog.getButton(AlertDialog.BUTTON_POSITIVE)
        mPositiveButton.setOnClickListener {
            // Programmatically closing the AlertDialog
            Toast.makeText(this, "Exited Alert Dialog", Toast.LENGTH_SHORT).show()


You can see that when the negative button is clicked, the AlertDialog is closed which is by default. When the positive button is clicked, the AlertDialog is closed which is bypassing a command to close it.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads