Alert Dialog is used very often when building applications. Usually, it is used to warn a user about an action he is about to take. Most of the time, those action are critical and irreversible, before deleting something for example.

A simple Alert Dialog in Android Studio would show the title, a warning or explanation message and buttons.

AlertDialog-AndroidStudio

Let us see how to build a simple Alert Dialog in Android Studio.

After creating a new empty project in Android Studio, we will start coding the Alert Dialog.

AndroidStudio-NewProject

Creating new project in Android Studio

First of all we need to create an Alert Dialog builder and set the parameters. As parameters we define the title and the message of the Alert Dialog.

Next, we define the function that will be executed if the user clicks in the positive button (in our case, button “Yes”).

Android Studio will help you to auto populate the onClick handler

Similarly, we will create the function to handle the action when the user clicks on the negative button (in our case button “No”).

And finally, we create the Alert Dialog from the builder and show it to the screen.

In our case, for demonstration purposes, we have decided to show the Alert Dialog immediately after the Android application is loaded. In real world situation, an Alert Dialog, usually appears after a certain action.

For the purposes of this tutorial, you need to create a text view in your Android application layout and give it an id of myText

Below, you will find the complete Java code of this tutorial:

This whole tutorial can be found in the below video:

Simple Alert Dialog in Android Studio – Tutorial

I hope this tutorial has helped you to understand the creation and the usage of a simple Alert Dialog in Android Studio.

If you have any question, please write them here or post them in the YouTube video above.

Thank you!

 

 

 

 

 


Leave a Reply

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