Skip to content
Related Articles

Related Articles

Improve Article

Alert Dialog with MultipleItemSelection in Android

  • Last Updated : 14 Dec, 2020

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.

Alert Dialog with MultipleItemSelection in Android

Steps to implement Alert Dialog with Multiple Item selection

Step 1: Create an empty activity project

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: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:

Alert Dialog with MultipleItemSelection in Android

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:

Alert Dialog with MultipleItemSelection in Android

  • 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 valus 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();
            }
        });
    }
}

Output: Run on Emulator

Want a more fast-paced & competitive environment to learn the fundamentals of Android?
Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!



My Personal Notes arrow_drop_up
Recommended Articles
Page :