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
.setTitle(context.getString(R.string.alert_dialog_title))
// Set Dialog message
.setMessage(
context.getString(
R.string.alert_dialog_message,
nameTextView.text.toString().capitalize(Locale.US)
)
)
// 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")
deleteItem()
}
// 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
builder.show()
}
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 builder.show()
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
.MaterialAlertDialogBuilder(context, R.style.ThemeOverlay_MaterialComponents_MaterialAlertDialog_Centered)