Thursday, April 5, 2018

android kotlin - AlertDialog multiple choice example

AlertDialog Multiple Choice
The AlertDialog is a subclass of Dialog that can display buttons, a simple text message, a list of items, single-choice items, multiple-choice items, etc. Developers can display a more complex View on the alert dialog window using a custom View.

The following android application development tutorial will demonstrate to us how we can display a list of multiple choice items in the alert dialog window as the content. And how developers can be notified when users select items from the multiple choice items list via the supplied listener. Android developers can add a click listener for the alert dialog multiple choice list items.

To create an alert dialog developers have to initialize an instance of AlertDialog.Builder object. This AlertDialog Builder object can define the alert dialog’s various properties such as button, message, icon, list and etc. Finally, they can create an AlertDialog using this builder instance.

So how can android developers display a list of multiple choice items with a click listener inside the alert dialog? The multiple-choice items list means users are allowed to select one or multiple items from the list. When they select an item from the list the previously selected items remain checked. They can change their selection and be allowed to select multiple items at a time.

By using the AlertDialog Builder instance developers can set its content to a list of multiple-choice items. The android SDK displays the list of multiple-choice items inside a dialog window in a good format and position.

The AlertDialog Builder object’s setMultiChoiceItems() method set a list of multiple-choice items to be displayed as the content of the alert dialog window. This method also allows us to set a click listener for the list items. So developers can be programmatically notified in real-time which items are selected from the list.

But commonly developers get the users selected/checked items on the positive button click event. They do not dismiss the alert dialog on item selection, so users can change their selection, add or remove items from the selection and submit their choices on the button click event.

This setMultiChoiceItems() method takes three arguments which are ‘items’, ‘checkedItems’, and ‘listener’. The ‘items’ argument represents an array of items, the ‘checkedItems’ represents a boolean array that defines the initially checked/selected items of the list, and the ‘listener’ argument passes a click event listener for the list items.

Practically the AlertDialog Builder setMultiChoiceItems() method renders a CheckBox group inside its window. Each item renders a CheckBox object inside the dialog window. Developers can set initially selected CheckBoxes or they can uncheck all CheckekBoxes on load. The boolean array’s ‘true’ and ‘false’ defines the corresponding item's check and uncheck status. Users can check an item, or multiple items and even can uncheck all items from the list and submit the dialog.

This android kotlin tutorial code is written in an android studio IDE. Copy the code and paste it into your android studio IDE and run it on an emulator to see how we create an AlertDialog with a multiple-choice list of items and allow users to select one or multiple items from them in an android application.

And how we can handle the click events for the alert dialog’s multiple-choice items list in an application. We displayed screenshots of the emulator screen, which also help you to understand the code without running it on an android device or emulator.
MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {
    private lateinit var context:MainActivity
    private lateinit var textView:TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Get the context
        context = this;

        // Get the widgets reference from XML layout
        textView = findViewById(R.id.textView)
        val button = findViewById<Button>(R.id.button)

        // Initialize an array of colors
        val arrayColors = arrayOf(
            "Red","Green","Yellow",
            "Black","Magenta","Pink"
        )

        // Initialize a boolean array of checked items
        val arrayChecked = booleanArrayOf(
            true,false,true,false,false,false
        )

        // Button click listener
        button.setOnClickListener{
            // Show the multiple choice list items on an alert dialog
            showDialog(arrayColors,arrayChecked)
        }
    }


    // Method to show an alert dialog with multiple choice list items
    private fun showDialog(
        arrayColors:Array<String>, arrayChecked:BooleanArray
    ){
        // Late initialize an alert dialog object
        lateinit var dialog:AlertDialog

        // Initialize a new instance of alert dialog builder object
        val builder = AlertDialog.Builder(context)

        // Set a title for alert dialog
        builder.setTitle("Choose favorite colors.")

        // Define multiple choice items for alert dialog
        builder.setMultiChoiceItems(arrayColors, arrayChecked) {
                dialog, which, isChecked ->
            // Update the clicked item checked status
            arrayChecked[which] = isChecked
        }

        // Set the positive/yes button click listener
        builder.setPositiveButton("OK") { _, _ ->
            // Do something when click positive button
            if((arrayChecked.count { it })>0){
                textView.text = "Your preferred colors\n"
                for (i in arrayColors.indices) {
                    val checked = arrayChecked[i]
                    if (checked) {
                        textView.append("${arrayColors[i]}\n")
                    }
                }
            }else{
                textView.text = "Selection is empty."
            }
        }

        // Set a neutral/cancel button for the dialog
        builder.setNeutralButton("Cancel"){_, _, ->
            textView.text = "Dialog canceled."
        }

        // Initialize the AlertDialog using builder object
        dialog = builder.create()

        // Finally, display the alert dialog
        dialog.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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rootLayout"
    android:background="#FEFEFA"
    android:padding="24dp">

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

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

</androidx.constraintlayout.widget.ConstraintLayout>
More android examples