Alert Dialog with MultipleItemSelection in Android
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.
Steps to implement Alert Dialog with Multiple Item selection
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:
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.
setMultiChoiceItems(listItems, checkedItems, new DialogInterface.OnMultiChoiceClickListener()
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.
Output: Run on Emulator