Signup/Sign In

AlertDialog with List

We know how to create an AlertDialog showing a simple message along with some buttons. In this lesson, we are going to learn how to add a multiple-options check list in an Alert Dialog. For this, we will be using the following method:

AlertDialog.Builder setMultiChoiceItems(P1,P2,P3)

The parameters used in the method are defined as follows:

  • P1: CharSequence[] items

    This parameter is used to display the text of items in the list.

  • P2: Boolean[] checkedItems

    This parameter is used to specify which items are checked. Remember, If this parameter is kept as null, it means no items are checked. If this parameter is not null, then it must be exactly of the same length as the array of items.

  • P3: DialogInterface.OnMultiChoiceClickListener

    This interface is used to notify whenever an item on the list is clicked. We need to override onClick(DialogInterface dialog, int id, boolean isChecked) method to use this interface.

Note: The dialog will not be dismissed when an item is clicked. It will only be dismissed if any button is clicked. If there are no buttons, then it's up to the user to dismiss the dialog programmatically.

Thus, we will first create an AlertDialog with all the necessary characteristics, as learned in AlertDialog topic. Now, instead of the message, we will show our checked list. So after mentioning all the necessary characteristics of an AlertDialog and before creating an AlertDialog using create() method, we need to define setMultiChoiceItems() method.

Let's learn and understand the code for it.

  1. We will first initialize our array with the site names that we want to display in our AlertDialog list.
    String sites[]={"StudyTonight","Facebook","Google","Youtube","Twitter"};
    boolean[] checkedSites = new boolean[]{false,false,false,false,false};
  2. Build AlertDialog.Builder object to set list and other characteristics in AlertDialog.
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    
    //Setting AlertDialog Characteristics
    builder.setTitle("Websites you have visited");
  3. We will call setMultiChoiceItems() method where we will pass our sites array, checked array and OnMultiChoiceClickListener() object.
    //Constructing the list in AlertDialog
    
    builder.setMultiChoiceItems(sites,checkedSites, new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                // Update the current item's checked status
                checkedSites[which] = isChecked;
               }
        });
  4. As we know, The dialog will not be dismissed when an item is clicked. It will only be dismissed if any button is clicked. Therefore, we will write the displaying items logic in setPositiveButton() method.
    //Set Positive Button
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getApplicationContext(),"OK button was pressed",Toast.LENGTH_LONG).show();
                tv.setText("Your selected Sites are: \n");
                for (int i = 0; i<checkedSites.length; i++){
                    boolean checked = checkedSites[i];
                    if (checked) {
                        tv.setText(tv.getText() + sitesList.get(i) + "\n");
                    }
                }
            }
        });
  5. Now, set the remaining characteristics of the AlertDialog and call create() method to build our AlertDialog with checked list. Below is the full XML and Java code.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.android.alertdialog.MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Open AlertDialog"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:onClick="openDialog"
        />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:text="Your selections will be displayed here"
        android:layout_below="@id/button"
        android:textSize="20sp"
        android:textColor="#25c"
        />
</RelativeLayout>

MainActivity.java

package com.example.android.alertdialog;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    String sites[]={"StudyTonight","Facebook","Google","Youtube","Twitter"};
    boolean[] checkedSites = new boolean[]{false,false,false,false,false};

    TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView) findViewById(R.id.textView2);
    }

    public void openDialog(View v){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        //Setting AlertDialog Characteristics
        builder.setTitle("Websites you have visited");

        //Building the list to be shown in AlertDialog
        builder.setMultiChoiceItems(sites,checkedSites, new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                // Update the current item's checked status
                checkedSites[which] = isChecked;
               }
        });

        //Set Positive Button
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getApplicationContext(),"OK button was pressed",Toast.LENGTH_LONG).show();
                tv.setText("Your selected Sites are: \n");
                for (int i = 0; i<checkedSites.length; i++){
                    boolean checked = checkedSites[i];
                    if (checked) {
                        tv.setText(tv.getText() + sites[i] + "\n");
                    }
                }
            }
        });
        //Set Negative Button
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getApplicationContext(),"Cancel button was pressed",Toast.LENGTH_LONG).show();
            }
        });
        //Set Neutral Button
        builder.setNeutralButton("Remind me later", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getApplicationContext(),"Remind me later button was pressed",Toast.LENGTH_LONG).show();
            }
        });

        //Creating AlertDialog
        AlertDialog dialog = builder.create();
        //Displaying AlertDialog
        dialog.show();

    }
}