Display Alert Dialog in Android

Display Alert Dialog in Android

An alert dialog is a popup window that is displayed in front of the current content. It asks the user to make a decision or enter additional details. An alert dialog can consist of title, content and a list of action buttons.

In the layout XML file, we added the Button which is used to display the alert dialog.

app/src/main/res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/myButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Open" />

</RelativeLayout>

An alert dialog can be constructed using the AlertDialog.Builder. A title and message can be set using the setTitle() and setMessage() methods.

An alert dialog can have three different action buttons.

ButtonDescription
PositiveUsed to confirm a action.
NegativeUsed to cancel a action.
NeutralUsed when doesn't know which action should be chosen at this moment.

An alert dialog can be displayed by using show() method.

app/src/main/java/com/example/app/MainActivity.kt

package com.example.app

import android.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import kotlinx.android.synthetic.main.activity_main.*

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

    private fun showAlertDialog()
    {
        val dialog = AlertDialog.Builder(this)
        dialog.setTitle("Update")
        dialog.setMessage("Are you sure want to update settings?")

        dialog.setPositiveButton("Yes") { _, _ ->
            Log.d("MY_APP", "Yes")
        }
        dialog.setNegativeButton("No") { _, _ ->
            Log.d("MY_APP", "No")
        }
        dialog.setNeutralButton("Remind me later") { _, _ ->
            Log.d("MY_APP", "Remind me later")
        }

        dialog.show()
    }
}

Leave a Comment

Cancel reply

Your email address will not be published.