Wednesday, April 4, 2018

android kotlin - AlertDialog setSingleChoiceItems 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.*
import android.graphics.Color


class MainActivity : AppCompatActivity() {

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

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


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

        // Initialize an array of colors
        val array = arrayOf("RED","GREEN","YELLOW","BLACK","MAGENTA","PINK")

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

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

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

            AlertDialog.Builder setSingleChoiceItems (CharSequence[] items,
                            int checkedItem,
                            DialogInterface.OnClickListener 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 the 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 items to be displayed.
                checkedItem int : specifies which item is checked. If -1 no items are checked.

                listener DialogInterface.OnClickListener : 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
        */

        // Set the single choice items for alert dialog with initial selection
        builder.setSingleChoiceItems(array,-1,{_,which->
            // Get the dialog selected item
            val color = array[which]

            // Try to parse user selected color string
            try {
                // Change the layout background color using user selection
                root_layout.setBackgroundColor(Color.parseColor(color))
                toast("$color color selected.")
            }catch (e:IllegalArgumentException){
                // Catch the color string parse exception
                toast("$color color not supported.")
            }

            // Dismiss the dialog
            dialog.dismiss()
        })


        // 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="#cac2bd"
    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"
        />
</LinearLayout>