Saturday, November 16, 2024
Google search engine
HomeLanguagesJavaAlert Dialog with MultipleItemSelection in Android

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.

Alert Dialog with MultipleItemSelection in Android

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.

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>


Output UI:

Alert Dialog with MultipleItemSelection in Android

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:

setMultiChoiceItems(listItems, checkedItems, new DialogInterface.OnMultiChoiceClickListener()

Parameters:

  • 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.

Java




import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
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(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, (dialog, which, 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", (dialog, which) -> {
                for (int i = 0; i < checkedItems.length; i++) {
                    if (checkedItems[i]) {
                        tvSelectedItemsPreview.setText(String.format("%s%s, ", tvSelectedItemsPreview.getText(), selectedItems.get(i)));
                    }
                }
            });
              
            // handle the negative button of the alert dialog
            builder.setNegativeButton("CANCEL", (dialog, which) -> {});
              
            // handle the neutral button of the dialog to clear the selected items boolean checkedItem
            builder.setNeutralButton("CLEAR ALL", (dialog, which) -> {
                Arrays.fill(checkedItems, false);
            });
              
            // create the builder
            builder.create();
              
            // create the alert dialog with the alert dialog builder instance
            AlertDialog alertDialog = builder.create();
            alertDialog.show();
        });
    }
}


Kotlin




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.drawable.image_logo)
  
            // 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 ->
                for (i in checkedItems.indices) {
                    if (checkedItems[i]) {
                        tvSelectedItemsPreview.text = String.format("%s%s, ", tvSelectedItemsPreview.text, selectedItems[i])
                    }
                }
            }
  
            // handle the negative button of the alert dialog
            builder.setNegativeButton("CANCEL") { dialog, which -> }
  
            // 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: Run on Emulator

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments