Android Alert Dialog with Checkboxes example


Let's see how we can add Checkboxes to an Alert Dialog box, we will create multiple checkboxes that can be selected with an OK and Cancel button with the help of setMultiChoiceItems listener on AlertDialog.Builder object.

Alert Dialog with CheckBoxes Example
Alert Dialog with CheckBoxes Example

Steps 1 : Create a Dialog object

Step 2 : Create a String Array to hold Items for Checkboxes and an ArrayList to hold items selected

Step 3 : Create AlertDialog.Builder object

Step 4 : Set the Title for AlertDialog

Step 5 : Now on builder object call setMultiChoiceItems

Step 6 : Set setPositiveButton and setNegativeButton button actions.

Step 7 : set dialog = builder.create(); and to display it call dialog.show();

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;

import java.util.ArrayList;


public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Dialog dialog;

        final String[] items = {" PHP", " JAVA", " JSON", " C#", " Objective-C"};


        final ArrayList itemsSelected = new ArrayList();

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

        builder.setTitle("Select Languages you know : ");

        builder.setMultiChoiceItems(items, null,
                new DialogInterface.OnMultiChoiceClickListener() {


                    @Override
                    public void onClick(DialogInterface dialog, int selectedItemId,
                                        boolean isSelected) {
                        if (isSelected) {

                            itemsSelected.add(selectedItemId);
                        } else if (itemsSelected.contains(selectedItemId)) {

                            itemsSelected.remove(Integer.valueOf(selectedItemId));
                        }
                    }
                })
                .setPositiveButton("Done!", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {

                        //Your logic when OK button is clicked
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {


                    }
                });

        dialog = builder.create();

        dialog.show();
    }
}