Thursday, April 5, 2018

android kotlin - AlertDialog multiple choice example

MainActivity.kt

package com.cfsuman.kotlinexamples

import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.app.AlertDialog
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {

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

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


    // Method to show an alert dialog with multiple choice list items
    private fun showDialog(){
        // Late initialize an alert dialog object
        lateinit var dialog:AlertDialog

        // 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)


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

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

        /*
            **** reference source developer.android.com ***

            AlertDialog.Builder setMultiChoiceItems (CharSequence[] items,
                            boolean[] checkedItems,
                            DialogInterface.OnMultiChoiceClickListener listener)

            Set a list of items to be displayed in the dialog as the content, you will be notified
            of the selected item via the supplied listener. The list will have a check mark
            displayed to the right of the text for each checked item. Clicking on an item
            in the list will not dismiss the dialog. Clicking on a button will dismiss the dialog.

            Parameters
                items CharSequence : the text of the items to be displayed in the list.

                checkedItems boolean : 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 DialogInterface.OnMultiChoiceClickListener : 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.

            Returns
                AlertDialog.Builder This Builder object to allow for chaining of calls to set methods
        */

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

            // Get the clicked item
            val color = arrayColors[which]

            // Display the clicked item text
            toast("$color clicked.")
        })


        // Set the positive/yes button click listener
        builder.setPositiveButton("OK") { _, _ ->
            // Do something when click positive button
            text_view.text = "Your preferred colors..... \n"
            for (i in 0 until arrayColors.size) {
                val checked = arrayChecked[i]
                if (checked) {
                    text_view.text = "${text_view.text}  ${arrayColors[i]} \n"
                }
            }
        }


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

        // Finally, display the alert dialog
        dialog.show()
    }
}



// Extension function to show toast message
fun Context.toast(message: String) {
    Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
activity_main.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"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/root_layout"
    android:background="#e7ece1"
    android:padding="16dp"
    android:orientation="vertical"
    >
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Options"
        android:textAllCaps="false"
        android:layout_gravity="center_vertical|center_horizontal"
        android:gravity="center"
        />
    <TextView
        android:id="@+id/text_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="@style/Base.TextAppearance.AppCompat.Large"
        android:textColor="#ff182b"
        android:layout_margin="25dp"
        />
</LinearLayout>