Android UI How to - Create AlertDialog and set title and message and Cancelable








Question

We would like to know how to create AlertDialog and set title and message and Cancelable.

Answer

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
//from w  w  w  . j  av  a 2s . c om
class AlertBox {
  public static void alertWarning(Context context, String message) {
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
    // set title
    alertDialogBuilder.setTitle("Your Title");
    // set dialog message
    alertDialogBuilder.setMessage(message).setCancelable(false)
        .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int id) {
            // if this button is clicked, close
            dialog.cancel();
          }
        });
    // create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();
    // show it
    alertDialog.show();
  }
}