AlertDialog in android

In this example will see how to display an Alert Dialog box in Android using Android Studio.

Alert Dialog box  is a small window which pops out on a screen to display particular events. This helps to draw users attention before moving further in the application. Alert dialog also comes with pre defined components. It usually have two buttons one is positive (OK) and another one is Negative  (Cancel) button. You can also define different actions on buttons clicks.

In this tutorial we will be creating two different Alert Dialog boxes. We need to create an object of AlertDialog Builder, which is inner class of AlertDialog to display the dialog box.

Few Methods names and Description

[table id=4 /]

In the given example below we will use one button. We will call method to display alert dialog box. Dialog box will open with message “Hello this is AlertDialog – Press OK to close”. Once you click on  “OK” button than dialog box will dismiss. Here we use dialog.cancel() method to dismiss the dialog window.

Example of Alert Dialog box in android

Alert Dialog

In the second example we will ask user to select their gender. Here we will use two buttons Positive and Negative. Once user clicks on Positive button than “Male” selected Toast occurs and if users clicks on Negative button than “Female” selected message will
Toast.

Output

Alert Dialog

Custom AlertDialog in android

In this example we will show how to use Custom Alert Dialog box. We are using EditText and Button inside Alert Box. Once user input the text and clicks on button, Toast message will be displayed.

Output