Sunday, August 16, 2015

How to create MultiChoice AlertDialog in Android

MainActivity.java

package com.cfsuman.androidtutorials;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import java.util.Arrays;
import java.util.List;


public class MainActivity extends Activity {
        private MainActivity mContext;
        private boolean[] mCheckedColors;
        private String[] mColors;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);

                // Get the context
                mContext = this;

                // Get the widgets reference from XML layout
                Button button = findViewById(R.id.button);
                TextView textView = findViewById(R.id.textView);

                // String array for alert dialog multi choice items
                mColors = new String[]{
                        "Red",
                        "Green",
                        "Blue",
                        "Purple",
                        "Olive"
                };

                // Boolean array for initial selected items
                mCheckedColors = new boolean[]{
                        false, // Red
                        true, // Green
                        false, // Blue
                        true, // Purple
                        false // Olive

                };


                // Set a button click listener
                button.setOnClickListener(v -> {
                        // Build an AlertDialog
                        AlertDialog.Builder builder = new AlertDialog
                                .Builder(mContext);

                        // Convert the color array to list
                        List<String> colorsList = Arrays.asList(mColors);


                        // Set multiple choice items for alert dialog
                        builder.setMultiChoiceItems(
                                mColors,
                                mCheckedColors,
                                (dialog, which, isChecked) -> {

                                // Update the current focused
                                // item's checked status
                                mCheckedColors[which] = isChecked;

                                // Get the current focused item
                                String currentItem = colorsList.get(which);

                                // Notify the current action
                                showToast(currentItem + " " + isChecked);
                        });


                        // Specify the dialog is not cancelable
                        builder.setCancelable(false);

                        // Set a title for alert dialog
                        builder.setTitle("Your preferred colors?");


                        // Set the positive/yes button click listener
                        builder.setPositiveButton(
                                "OK", (dialog, which) -> {

                                // Do something when click positive button
                                textView.setText(
                                        "Your preferred color(s) ...");

                                for (int i = 0; i<mCheckedColors.length; i++){
                                        boolean checked = mCheckedColors[i];
                                        if (checked) {
                                                textView.append("\n");
                                                textView.append(
                                                        colorsList.get(i));
                                        }
                                }
                        });


                        // Set the negative/no button click listener
                        builder.setNegativeButton(
                                "No", (dialog, which) -> {
                                // Do something won negative button click
                        });


                        // Set the neutral/cancel button click listener
                        builder.setNeutralButton(
                                "Cancel", (dialog, which) -> {
                                // Do something on neutral button click
                        });


                        AlertDialog dialog = builder.create();
                        // Display the alert dialog on interface
                        dialog.show();
                });
        }



        // Method to show toast message
        private void showToast(String message){
                Toast.makeText(
                        mContext,message,Toast.LENGTH_SHORT).show();
        }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#DCDCDC"
    android:padding="32dp">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show AlertDialog"
        android:textAllCaps="false"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:fontFamily="sans-serif"
        android:textSize="24sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button"
        tools:text="TextView" />

</androidx.constraintlayout.widget.ConstraintLayout>