How to Display an Alert Dialog

In this post, I’m going to show you how to create and display a simple AlertDialog. The dialog I’m going to implement can be seen below:

And the following is the code snippet for this dialog:

Here, I created a dialog with three buttons using builder pattern. First, through setCancellable() method, I set whether the dialog can be canceled using back button or clicking outside of the dialog. Then, I set a dialog title and message, together with a drawable as an icon to be displayed left to the dialog title. Following these, I set all possible three buttons (positive, negative, and neutral) together with their on-click listeners. The corresponding onClick() method is fired when you click one of them. By the way, you don’t have to display all three buttons; you can just implement the ones you want to show. After the buttons and their on-click listeners, I also set listeners for “cancel” (remember we set the dialog as cancellable) and “dismiss” events. When you cancel the dialog through the ways I stated above, onCancel() method is fired. And when the dialog is dismissed through clicking any of the buttons we set, onDismiss() method is fired.

AlertDialog.Builder class provides many other options for the customization of dialog. You can see all of them here in the docs:

Leave a Reply

Your email address will not be published. Required fields are marked *