How to create a simple Alert Dialog in Android?

Alert Dialogs are useful to show warning to users and ask for their confirmations. Simply put, alert dialogs are popups with a title and a message with positive and negative actions.

Simple Alert Dialog

To create an alert dialog, we need to use the AlertDialog.Builder class. You can call the AlertDialog.Builder using the context of the MainActivity.

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

A simple alert dialog has three main components:

  1. Title
    This is optional and can be used when the content area is occupied by a detailed message, a list, or custom layout.

    builder.setTitle("Are you sure?");
  2. Content area
    This can display a message, a list, or other custom layout.

    builder.setMessage("Are you sure you want to delete this item?");
  3. Action buttons
    There are three action buttons that can be used in a dialog: the positive, the negative and the neutral button.We can use the positive button using the setPositiveButton() method and passing the text and the click action.

    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
         @Override
         public void onClick(DialogInterface dialogInterface, int i) {
              // do some action
         }
     });
     builder.show();

    By using the setNegativeButton() method, we can set a cancel action to the dialog.

    builder.setNegativeButton("No, thanks", new DialogInterface.OnClickListener() {
         @Override
         public void onClick(DialogInterface dialogInterface, int i) {
              // dismiss dialog
              dialogInterface.dismiss();
         }
     });
     builder.show();

Below is the final method to show the dialog:

public void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Confirm Delete");
        builder.setMessage("Are you sure you want to delete this item?");

        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                // do some action
            }
        });
        builder.show();
        builder.setNegativeButton("No, thanks", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                // dismiss dialog
                dialogInterface.dismiss();
            }
        });
}

Get the demo for the Alert Dialogs at Github.