Alert Dialog with MultipleItemSelection in Android

27 Oct, 2021
In the previous article Alert Dialog with SingleItemSelection in Android, we have seen that 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.
Step 1: Create an empty activity project
Create an empty activity Android Studio Project. And select Java as a programming language.
To create an empty activity Android Studio project refer to Android | How to Create/Start a New Project in Android Studio?
Step 2: Working with the activity_main.xml
The main layout includes one simple Button and a TextView widget. TextView is implemented to preview the selected items from the list.
Invoke the following code to build UI:
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/colorPrimary"        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>
 
 
Output UI:
 
 
Step 3: Working with the MainActivity.java file
 
There is a need to understand the parts of the multiple item selection alert dialog. Look at the following image to know the parts:
The function that needs to implement the multiple item selection for alert dialog is discussed below.
Syntax:
setMultiChoiceItems(listItems, checkedItems, new DialogInterface.OnMultiChoiceClickListener()
Parameters:
listItems: are the items to be deisplayed on the alert dialog.
checkedItems: it is the boolean array which maintains the selected values as true, and unselected values as false.
DialogInterface.OnMultiChoiceClickListener(): which is callback when change in the selection of items takes place.
Invoke the following code to implement the things. Comments are added for better understanding.
 
Java
import androidx.appcompat.app.AlertDialog;import androidx.appcompat.app.AppCompatActivity;import android.annotation.SuppressLint;import android.content.DialogInterface;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;import java.util.Arrays;import java.util.List; public class MainActivity extends AppCompatActivity {     @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);         // UI widgets button and        Button bOpenAlertDialog = findViewById(R.id.openAlertDialogButton);        final TextView tvSelectedItemsPreview = findViewById(R.id.selectedItemPreview);         // initialise the list items for the alert dialog        final String[] listItems = new String[]{"C", "C++", "JAVA", "PYTHON"};        final boolean[] checkedItems = new boolean[listItems.length];         // 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        final List<String> selectedItems = Arrays.asList(listItems);         // handle the Open Alert Dialog button        bOpenAlertDialog.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                 // initially set the null for the text preview                tvSelectedItemsPreview.setText(null);                 // initialise the alert dialog builder                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);                               // set the title for the alert dialog                builder.setTitle("Choose Items");                               // set the icon for the alert dialog                builder.setIcon(R.drawable.image_logo);                 // now this is the function which sets the alert dialog for multiple item selection ready                builder.setMultiChoiceItems(listItems, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {                    @Override                    public void onClick(DialogInterface dialog, int which, boolean isChecked) {                        checkedItems[which] = isChecked;                        String currentItem = selectedItems.get(which);                    }                });                 // alert dialog shouldn't be cancellable                builder.setCancelable(false);                 // handle the positive button of the dialog                builder.setPositiveButton("Done", new DialogInterface.OnClickListener() {                    @SuppressLint("SetTextI18n")                    @Override                    public void onClick(DialogInterface dialog, int which) {                        for (int i = 0; i < checkedItems.length; i++) {                            if (checkedItems[i]) {                                tvSelectedItemsPreview.setText(tvSelectedItemsPreview.getText() + selectedItems.get(i) + ", ");                            }                        }                    }                });                 // handle the negative button of the alert dialog                builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {                    @Override                    public void onClick(DialogInterface dialog, int which) {                     }                });                 // handle the neutral button of the dialog to clear                  // the selected items boolean checkedItem                builder.setNeutralButton("CLEAR ALL", new DialogInterface.OnClickListener() {                    @Override                    public void onClick(DialogInterface dialog, int which) {                        for (int i = 0; i < checkedItems.length; i++) {                            checkedItems[i] = false;                        }                    }                });                 // create the builder                builder.create();                 // create the alert dialog with the                  // alert dialog builder instance                AlertDialog alertDialog = builder.create();                alertDialog.show();            }        });    }}
  
 
rajeev0719singh
android
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.