Android UI How to - Create AlertDialog with various default parameters








Question

We would like to know how to create AlertDialog with various default parameters.

Answer

//ww w .ja va  2  s.co  m
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;

class Alert {
  public interface OnClick {
    public abstract void action(Context context);
  }

  /**
   *
   * @param context
   *          Context handle
   * @param message
   *          Message for show box
   */
  public static void show(Activity context, String message) {
    show(context, "", message);
  }

  public static void show(Activity context, String title, String message) {
    show(context, title, message, -1);
  }

  public static void show(Activity context, String title, String message,
      int icon_resource) {
    show(context, title, message, icon_resource, null);
  }

  /**
   * @param context
   *          Context handle
   * @param title
   *          Title for top of show box (optional)
   * @param message
   *          Message for show box
   * @param on_close
   *          Callback to perform when box is dismissed
   */
  public static void show(final Activity context, final String title,
      final String message, final int icon_resource, final OnClick on_close) {
    context.runOnUiThread(new Runnable() {
      public void run() {
        int my_icon_resource = icon_resource;
        if (icon_resource == -1) {
          my_icon_resource = android.R.drawable.ic_dialog_info;
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setMessage(message).setIcon(my_icon_resource).setTitle(title)
            .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int id) {
                dialog.dismiss();
                if (on_close != null) {
                  on_close.action(context);
                }
              }
            }).create().show();
      }
    });
  }
  public static void error(Activity context, String message) {
    show(context, "Whoops!", message);
  }
  public static void error(Activity context, String title, String message) {
    show(context, title, message, android.R.drawable.ic_dialog_alert);
  }
}