Alert Dialog - Material Design Component

Alert Dialog in Android is a blocking window shown to the user for immediate user attention and interaction.

To build and show an alert dialog, we will be using MaterialAlertDialogBuilder. It is an extension of AlertDialog.Builder that we are familiar with but provides Material theming to the dialog.

The below pictures shows the subtle differences in using MaterialAlertDialogBuilder and AlertDialog.Builder.

Dialog built with MaterialAlertDialogBuilder

Dialog built with AlertDialog.Builder

Before, we start implementing the Material Alert Dialog, add Material Design Components to our project. Now, let's create the Alert Dialog.

private fun showAlert(context: Context) {
    // Build the dialog
    val builder = MaterialAlertDialogBuilder(context)
        // Set Dialog title
        // Set Dialog message
        // Set OK button
        .setPositiveButton(context.getString(R.string.button_text_ok)) { _, _ ->
            if (DBG) Log.d(TAG, "User wants to delete the item from the cart")
        // Set Cancel button
        .setNegativeButton(context.getString(R.string.button_text_cancel)) { _, _ ->
            if (DBG) Log.d(TAG, "User continues with the cart")
    // Show the alert dialog

Set the title and message for the Alert Dialog. The title is shown at the top in bold and the message is shown below it. In addition to that, show affirmative action as a positive button and another button to cancel the dialog.

Once, show method is called, the Alert dialog is created and shown to the user. Nothing important but one thing to remember during the implementation is that returns an AlertDialog and not MaterialAlertDialog as there is not MaterialAlertDialog component available as of now.


If we are interested to center the title of the Alert Dialog as shown in the figure above, we can set a pre-defined style using the MaterialAlertDialogBuilder.


Popular posts from this blog

How to Read Metadata from AndriodManifest File

Add Spacing to Recycler View Linear Layout Manager Using Item Decoration

Create Assets Folder, Add Files and Read Data From It

How to Change Material Chip Text Size, Text Style and Font

Change Snackbar Position When Bottom App Bar or Bottom Navigation View Is Present