Alert Dialog with MultipleItemSelection in Android
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.
Step By Step Implementation
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.
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.
The function that needs to implement the multiple item selection for alert dialog is discussed below.
setMultiChoiceItems(listItems, checkedItems, new DialogInterface.OnMultiChoiceClickListener()
- listItems: are the items to be displayed on the alert dialog.
- checkedItems: it is the boolean array that maintains the selected values as true, and unselected values as false.
- DialogInterface.OnMultiChoiceClickListener(): This is a callback when a change in the selection of items takes place.
Invoke the following code to implement the things. Comments are added for better understanding.