Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java
  • Android
  • Kotlin
  • Flutter
  • Dart
  • Android with Java
  • Android Studio
  • Android Projects
  • Android Interview Questions
Open In App
Next Article:
Alert Dialog with MultipleItemSelection in Android
Next article icon

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
Alert Dialog with MultipleItemSelection in Android

A

adityamshidlyali
Improve
Article Tags :
  • Java
  • Technical Scripter
  • Kotlin
  • Android
  • Technical Scripter 2020
  • Kotlin Android
  • Java-Android
Practice Tags :
  • Java

Similar Reads

    Alert Dialog with SingleItemSelection in Android
    Alert Dialogs are the UI elements that pop up when the user performs some crucial actions with the application. These window-like elements may contain multiple or single items to select from the list or have the error message and some action buttons. In this article, it's been discussed how to imple
    4 min read
    MultiAutoCompleteTextView in Android with Example
    MultiAutoCompleteTextView is an editable TextView, extending AutoCompleteTextView. In a text view, when the user starts to type a text, MultiAutoCompleteTextView shows completion suggestions for the substring of the text and it is useful for the user to select the option instead of typing. This feat
    6 min read
    How to Set Buttons Inside an Alert Dialog in Android?
    In this article, we are going to see how can we set two buttons inside an Alert Dialog. For example, we can see when an alert dialog is pop up then their two types of buttons available one is the Ok or Positive Button another one is Cancel or Negative Button. Alert dialogs are most frequently used i
    4 min read
    How to Change Alert Dialog Position on Screen in Android?
    AlertDialog in Android is an alert message that appears in the form of a pop-up consisting of four elements namely a title, a message, a positive button, and a negative button. The positive and the negative buttons are clickable and can be programmed for performing an action. However, the AlertDialo
    2 min read
    How to Implement Loading AlertDialog in Android?
    AlertDialog is defined as the small window that shows a particular message to the user when the user performs or commits certain action. In this article, we are going to build a simple android application in which we learn how to implement a Loading AlertDialog that means whenever the user clicks on
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences