Open In App

Alert Dialog with MultipleItemSelection in Android

Last Updated : 10 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In the previous article Alert Dialog with SingleItemSelection in Android, we have seen how the alert dialog is built for single item selection. In this article, it's been discussed how to build an alert dialog with multiple item selection. Multiple Item selection dialogs are used when the user wants to select multiple items at a time. Have a look at the following image to differentiate between Single Item selection and Multiple Item selection alert dialogs.

Alert Dialog with MultipleItemSelection in Android


Implementation of Alert Dialog with MultipleItemSelection

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.

The code for that has been given in both Java and Kotlin Programming Language for Android.


Step 2: Working with the XML Files

Next, go to the activity_main.xml file, which represents the UI of the project. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.

activity_main.xml:

XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity"
    tools:ignore="HardcodedText">

    <Button
        android:id="@+id/openAlertDialogButton"
        android:layout_width="256dp"
        android:layout_height="60dp"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="64dp"
        android:backgroundTint="@color/purple_500"
        android:text="OPEN ALERT DIALOG"
        android:textColor="@android:color/white"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/selectedItemPreview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:textColor="@android:color/black"
        android:textSize="18sp" />
</LinearLayout>

Design UI:

output-ui-alert-box-multiselect


Step 3: Working with the MainActivity File

Go to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail.

Alert-Dialog-with-MultipleItemSelection-in-Android


The function that needs to implement the multiple item selection for alert dialog is discussed below.

Syntax:

// documentation code
public Builder setMultiChoiceItems(Char Sequence[] items, Boolean[] checkedItems, final OnMultiChoiceClickListener listener) {
// other codes here
}

// your implementation
builder.setMultiChoiceItems(items, checkedItems) { dialog, which, isChecked ->
// your code here
}

Parameters:

  • items – the text of the items to be displayed in the list.
  • checkedItems – specifies which items are checked. It should be null in which case no items are checked. If non null it must be exactly the same length as the array of items.
  • listener – notified when an item on the list is clicked. The dialog will not be dismissed when an item is clicked. It will only be dismissed if clicked on a button, if no buttons are supplied it's up to the user to dismiss the dialog.

Invoke the following code to implement the things. Comments are added for better understanding.

Java
package org.geeksforgeeks.demo;

import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity {

    private String[] listItems = {"C", "C++", "JAVA", "PYTHON"};
    private boolean[] checkedItems = new boolean[listItems.length];
    private StringBuilder selectedItemsPreview = new StringBuilder();
    
    private Button bOpenAlertDialog;
    private TextView tvSelectedItemsPreview;

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

        bOpenAlertDialog = findViewById(R.id.openAlertDialogButton);
        tvSelectedItemsPreview = findViewById(R.id.selectedItemPreview);

        bOpenAlertDialog.setOnClickListener(v -> {
            
            // Clear any previous selections
            selectedItemsPreview.setLength(0); 
            tvSelectedItemsPreview.setText(null);

            // Build the AlertDialog
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this)
                    .setTitle("Choose Items")
                    .setIcon(R.mipmap.ic_launcher_round)
                    .setCancelable(false)
                    .setMultiChoiceItems(listItems, checkedItems, (dialog, which, isChecked) -> checkedItems[which] = isChecked)
                    .setPositiveButton("Done", (dialog, which) -> {
                        selectedItemsPreview.append("Selected Items are:\n");
                        for (int i = 0; i < checkedItems.length; i++) {
                            if (checkedItems[i]) {
                                selectedItemsPreview.append(listItems[i]).append("\n");
                            }
                        }
                        tvSelectedItemsPreview.setText(selectedItemsPreview.toString());
                    })
                    .setNegativeButton("CANCEL", (dialog, which) -> dialog.dismiss())
                    .setNeutralButton("CLEAR ALL", (dialog, which) -> Arrays.fill(checkedItems, false));

            AlertDialog alertDialog = builder.create();
            alertDialog.show();
        });
    }
}
Kotlin
package org.geeksforgeeks.demo

import android.content.DialogInterface
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import java.util.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // UI widgets button and
        val bOpenAlertDialog = findViewById<Button>(R.id.openAlertDialogButton)
        val tvSelectedItemsPreview = findViewById<TextView>(R.id.selectedItemPreview)

        // initialise the list items for the alert dialog
        val listItems = arrayOf("C", "C++", "JAVA", "PYTHON")
        val checkedItems = BooleanArray(listItems.size)

        // copy the items from the main list to the selected
        // item list for the preview if the item is checked
        // then only the item should be displayed for the user
        val selectedItems = mutableListOf(*listItems)

        // handle the Open Alert Dialog button
        bOpenAlertDialog.setOnClickListener {
            // initially set the null for the text preview
            tvSelectedItemsPreview.text = null

            // initialise the alert dialog builder
            val builder = AlertDialog.Builder(this)

            // set the title for the alert dialog
            builder.setTitle("Choose Items")

            // set the icon for the alert dialog
            builder.setIcon(R.mipmap.ic_launcher_round)

            // now this is the function which sets the alert
            // dialog for multiple item selection ready
            builder.setMultiChoiceItems(listItems, checkedItems) { dialog, which, isChecked ->
                checkedItems[which] = isChecked
                val currentItem = selectedItems[which]
            }

            // alert dialog shouldn't be cancellable
            builder.setCancelable(false)

            // handle the positive button of the dialog
            builder.setPositiveButton("Done") { dialog, which ->
                tvSelectedItemsPreview.text = "Selected Items are:\n"
                for (i in checkedItems.indices) {
                    if (checkedItems[i]) {
                        tvSelectedItemsPreview.text = String.format("%s%s\n",
                        tvSelectedItemsPreview.text, selectedItems[i])
                    }
                }
            }

            // handle the negative button of the alert dialog
            builder.setNegativeButton("CANCEL") { dialog, which ->
                // your code here
            }

            // handle the neutral button of the dialog to clear
            // the selected items boolean checkedItem
            builder.setNeutralButton("CLEAR ALL") { dialog: DialogInterface?, which: Int ->
                Arrays.fill(checkedItems, false)
            }

            // create the builder
            builder.create()

            // create the alert dialog with the alert dialog
            // builder instance
            val alertDialog = builder.create()
            alertDialog.show()
        }
    }
}

Output:


Next Article

Similar Reads