1

Using Android API 14 or higher, what is the easiest way to make a dialog box? All I want is a few lines of text, OK button, and Cancel button. The Cancel button closes the dialog, the OK button performs some method that I have.

The reason I ask is because I'm going through a few different tutorial books and many of them seem to make dialog creation an overly complicated process. So I want the absolute simplest way to do this (fewest lines of code).

Michael Celey
  • 12,645
  • 6
  • 57
  • 62
Ethan Allen
  • 14,425
  • 24
  • 101
  • 194

1 Answers1

3

The proper way is use a DialogFragment but if you want the fewest lines of code then the below code will work just fine:

public void showMessageDialog(Context context, int message, int title) {
    new AlertDialog.Builder(context)
    .setTitle(title)
    .setMessage(message)
    .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // TODO: Ok click stuff
        }
    })
    .setNegativeButton(R.string.cancel, null)
    .show();
}

The variables message and title are both String resource identifiers.

Michael Celey
  • 12,645
  • 6
  • 57
  • 62