How to create a custom alert dialog

Florence
2 min readJul 4, 2022

--

An alert dialog is a dialog box or a small popup window that is mostly displayed on top of the user’s current screen.It can be used to display information to the user and also prompt a user to make a decision.

You can create an alert dialog using the following methods:
1. Android AlertDialog class
2. Material Design — MaterialAlertDialogBuilder class
3. In situations where the design of the alert dialog doesn’t look like what is provided by the existing methods, you can create your own custom alert dialog

In this article we will go through the steps to create a custom alert dialog that is displayed once a user wishes to logout.
The design of the alert dialog will look as follows:

Steps to implement the alert dialog:

  1. First we will create a logout button, that a user clicks on and prompts an alert dialog to pop up.
    This is how it will appear on screen

We will create an xml layout for the logout button

2. We will then create an xml layout for the alert dialog

3. In the logout button setonClickListener we will create a new AlertDialog.Builder object.

4. We will then inflate the layout file dialog_confirm_logout.xml

5. We will set the view of the dialog box to the layout file dialog_confirm_logout.xml

6. We now need a way to dismiss the alert dialog, when the user clicks on the NO button.

7. Lastly a user should have the ability to logout when they click on YES button.

8. Create a new AlertDialog object.

9. Show the dialog box.

10. The whole code will now look like this

That’s all for today.

Happy Coding!!

--

--