AlertDialog

A Dialog is small window that prompts the user to a decision or enter additional information. Some times in your application, if you wanted to ask the user about taking a decision between yes or no in response of any particular action taken by the user, by remaining in the same activity and without changing the screen, you can use AlertDialog.

How to create AlertDialog:

public void showAlertDialog(View view) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Alert Dialog");
    builder.setMessage("This is demo AlertDialog");

    builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            dialogInterface.dismiss();
            Toast.makeText(MainActivity.this, "You clicked on Ok", Toast.LENGTH_SHORT).show();
        }
    });
    builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            dialogInterface.dismiss();
            Toast.makeText(MainActivity.this, "You clicked on Cancel", Toast.LENGTH_SHORT).show();
        }
    });

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

    // below line keep dialog displayed when rotate screen, iff these lines not present
    // an exception will through, so keep best practice to include these lines
    WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
    lp.copyFrom(dialog.getWindow().getAttributes());
    lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
    lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
    dialog.getWindow().setAttributes(lp);
}


Common Method's

Method Description
setTitle(...) This method is used to set the title of AlertDialog. You can pass either string resource id or direct string.
setMessage(...) This method is used to set the message for AlertDialog. You can pass either string resource id or direct string.
setIcon(...) This method is used to set the icon over AlertDialog. Pass drawable resource id.
setCancelable(...) This method sets the property that the dialog can be cancelled or not
setMultiChoiceItems(...) This method sets list of items to be displayed in the dialog as the content. The selected option will be notified by the listener.
setOnCancelListener(...) This method Sets the callback that will be called if the dialog is cancelled.
setPositiveButton(...) This method set Positive button like Ok or Done along with it you can pass ClickListner in it.
setNegativeButton(...) This method set Positive button like Cancel or Finish etc... along with it you can pass ClickListner in it.

Now we will learn to create MultiChoiceAlertDialog, following method will tell you how to create multiple choice alert dialog.

Note: Do not use setMessage() method other wise choice list will not display.

public void showMultiChoiceDialog(View view) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Multi Choice Alert Dialog");

    final String[] fruits = getResources().getStringArray(R.array.fruits);
    final boolean[] itemSelected = new boolean[fruits.length];
    builder.setMultiChoiceItems(R.array.fruits, itemSelected, new DialogInterface.OnMultiChoiceClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int which, boolean isChecked) {
            StringBuffer strBuff = new StringBuffer();
            for (int index = 0; index < itemSelected.length; index++) {
                if(itemSelected[index]) {
                    strBuff.append(fruits[index] + ", ");
                }
            }
            Toast.makeText(MainActivity.this, "You selected fruit: " + strBuff.toString(), Toast.LENGTH_SHORT).show();
        }
    });

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

    // below line keep dialog displayed when rotate screen, iff these lines not present
    // an exception will through, so keep best practice to include these lines
    WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
    lp.copyFrom(dialog.getWindow().getAttributes());
    lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
    lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
    dialog.getWindow().setAttributes(lp);
}


Now we will learn to create SingleChoiceAlertDialog, following method will tell you how to create single choice alert dialog.

Note: Do not use setMessage() method other wise choice list will not display.

public void showSingleChoiceDialog(View view) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Single Choice Alert Dialog");

    final String[] fruits = getResources().getStringArray(R.array.fruits);
    builder.setSingleChoiceItems(R.array.fruits, 0, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int which) {
            Toast.makeText(MainActivity.this, "You selected fruit: " + fruits[which], Toast.LENGTH_SHORT).show();
        }
    });
    AlertDialog dialog = builder.create();
    dialog.show();

    // below line keep dialog displayed when rotate screen, iff these lines not present
    // an exception will through, so keep best practice to include these lines
    WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
    lp.copyFrom(dialog.getWindow().getAttributes());
    lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
    lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
    dialog.getWindow().setAttributes(lp);
}

Let's have a look of strings.xml and find fruits string array:

<resources>
    <string name="app_name">DialogExample</string>
    <string-array name="fruits">
        <item>Apple</item>
        <item>Orange</item>
        <item>Mango</item>
        <item>Grapes</item>
        <item>Guava</item>
    </string-array>
</resources>