Open In App

Automatic Dialog Dismiss in Android

Last Updated : 16 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Imagine a scenario where a dialog appears, but the user doesn’t interact with it. The dialog could potentially block other actions or disrupt the user experience. To address this issue, developers can employ a technique known as automating dialog dismissal using timers. In this article, we will explore how to set up a timer to automatically dismiss dialog boxes in Android applications. A sample video is given below to get an idea about what we are going to do in this article.

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. Note that select Kotlin as the programming language.

Step 2: Change the StatusBar Color

Navigate to app > res > values > themes > themes.xml and add the below code under the style section in the themes.xml file.

<item name="android:statusBarColor" tools:targetApi="l">#308d46</item>

Step 3: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to the activity_main.xml file. In this code, we are going to implement a Button by clicking this button an Alert Dialog will pop up and Automatically dismiss in 5 seconds.

activity_main.xml:

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/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="open an Alert Dialog for 5 seond"/>
  
</LinearLayout>


Step 4: Working with the MainActivity.kt file

In this step, we are going to apply onclickListner to the button so that when the user clicks the button an alert dialog will open and automatically dismiss after 5 seconds. Below is the code for MainActivity.kt. Comments are added for a better understanding of the Code. The below function is Responsible for populating the alert dialog and dismiss it after 5 seconds.

  // Function to open the AlertDialog and dismiss after 5 seconds
fun openAlertDialog() {
// Create an AlertDialog.Builder
val builder = AlertDialog.Builder(this)
builder.setTitle("Auto Dismiss Dialog")
builder.setMessage("This dialog will automatically dismiss in 5 seconds.")
// Set a positive button and its click listener
builder.setPositiveButton("OK") { dialog, which ->
// Handle positive button click if needed
dialog.dismiss()
}
// Create the AlertDialog
alertDialog = builder.create()
// Show the AlertDialog
alertDialog.show()
// Schedule the dismissal after a certain delay
val handler = Handler()
handler.postDelayed({
if (alertDialog.isShowing) {
alertDialog.dismiss()
}
}, dismissalDelayMillis.toLong())
}

Below is the Implementation of MainActivity.kt.

MainActivity.kt:

Kotlin




package com.example.gfg
  
import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.widget.Button
import androidx.appcompat.app.AlertDialog
  
class MainActivity : AppCompatActivity() {
    private lateinit var alertDialog: AlertDialog
    private lateinit var button: Button
    private val dismissalDelayMillis = 5000 // 5 seconds
  
    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        // Initialize the button
        button = findViewById<Button>(R.id.btn)
  
        // Set a click listener for the button
        button.setOnClickListener {
            openAlertDialog()
        }
    }
  
    // Function to open the AlertDialog and dismiss after 5 seconds
    fun openAlertDialog() {
        // Create an AlertDialog.Builder
        val builder = AlertDialog.Builder(this)
        builder.setTitle("Auto Dismiss Dialog")
        builder.setMessage("This dialog will automatically dismiss in 5 seconds.")
        // Set a positive button and its click listener
        builder.setPositiveButton("OK") { dialog, which ->
            // Handle positive button click if needed
            dialog.dismiss()
        }
        // Create the AlertDialog
        alertDialog = builder.create()
        // Show the AlertDialog
        alertDialog.show()
        // Schedule the dismissal after a certain delay
        val handler = Handler()
        handler.postDelayed({
            if (alertDialog.isShowing) {
                alertDialog.dismiss()
            }
        }, dismissalDelayMillis.toLong())
    }
}


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads