Alert Dialog Box Code for Android Studio

In this tutorial you will learn to create Alert Dialog Box in Android Studio.

Android Alert Dialog Box code

An Alert Dialog box is a small box like window which displays a prompt message and then receives information from the user. It usually gives two choices and as options and performs a task based on the option chosen. It is generally used to display alert messages such as Warning! Your file will be deleted! or something like that.

Inserting an Alert Dialog Box in your app

To display an Alert Dialog Box. first you will have to use the AlertDialog.Builder class and BUILD an alertDialogBuilder object, as shown in the example below :-

Setting Title of Alert Dialog Box

To set Title, use the SetTitle function.

Setting Message to be displayed in Alert Dialog Box

Usually a small chunk of information is displayed in brief inside the Dialog Box. To set this message to be displayed, use the SetMessage function.

Setting Positive Button

Setting Negative Button

In place of task to be executed, you can either leave it empty or you can create some additional OnClickListener.

Finally Creating the AlertDialogBox

After building our dialogbox, finally you have to create it using the .create() option and display it using .show()

The Full Java Code along with the XML layout for the above example is shown below:-

  • First Create a new project in Android Studio
  • File ⇒ New Android ⇒ Application Project
  • Then Open src -> package -> MainActivity.java and then add following code :

JAVA (MainActivity.java)

  •  Now Open res -> layout -> activity_main.xml and then add following code :

XML (activity_main.xml)

You can directly copy paste these snippets to your android studio, and they should work perfectly. Just save and run your project. You can also try to play with other dialog settings on your own and see the corresponding changes accordingly. There are a variety of properties available which can be changed to make your Alert Dialog Box more materialized and fancy looking.

Output:

Finally, run this project.

This is how Alert Dialog Box Code snippet for Android Studio

Alert Dialog Box Code Alert Dialog Box Code

For a more detailed guide, you can also visit android’s official guide below:-

https://developer.android.com/reference/android/app/AlertDialog

Comment down below if you are facing any problems.

 

Also Read:-

Leave a Reply

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