Android for Beginners
About Lesson

Alert Dialogs are a common feature in many applications. They are used to show messages, and warnings, or get user input. This blog post will explore how to create Alert Dialogs in Android.

 

Step 1: Creating an AlertDialog.Builder

The first step in creating an Alert Dialog is to create an instance of AlertDialog.Builder. This class provides a convenient way to set the various fields of an Alert Dialog and create the Alert Dialog.

Here’s a simple example of how to create an AlertDialog.Builder:

AlertDialog.Builder builder = new AlertDialog.Builder(this);

 

In this code, this refers to the current Context (an Activity or a Fragment).

 

Step 2: Setting the Dialog Properties

Once the AlertDialog.Builder is created, we can use it to set the properties of the Alert Dialog. This includes the title, message, and buttons of the dialog.

Here’s how to set these properties:

builder.setTitle("Alert Dialog Title");
builder.setMessage("Alert Dialog Message");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});

 

In this code, setTitle and setMessage are used to set the title and message of the Alert Dialog, respectively. setPositiveButton and setNegativeButton are used to create the dialog’s positive (OK) and negative (Cancel) buttons. The DialogInterface.OnClickListener passed to these methods will be called when the user clicks the corresponding button.

 

Step 3: Showing the Dialog

The final step is to create the AlertDialog from the AlertDialog.Builder and show it. This is done using the create and show methods of the AlertDialog.Builder.

Here’s how to show the Alert Dialog:

AlertDialog dialog = builder.create();
dialog.show();

 

In this code, create is used to create the AlertDialog from the AlertDialog.Builder, and show is used to display the Alert Dialog.