Android/Kotlin แสดงไดอะล็อกตัวเลือกด้วย setItems()

แสดงไดอะล็อกด้วย AlertDialog.setItems()

ไฟล์ที่เกี่ยวข้อง

  • activity_main.xml
  • MainActivity.kt

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
        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:id="@+id/layoutRoot"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

    <Button
            android:id="@+id/btnShowAlert"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Show Alert"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.kt

package com.phaisarn.myapplication

import android.graphics.Color
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AlertDialog
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

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

        // when button is clicked, show the alert
        btnShowAlert.setOnClickListener {
            // Initialize an array of colors
            val arrColor = arrayOf("RED", "GREEN", "YELLOW", "BLACK", "MAGENTA")

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

            builder.setItems(arrColor) { _, which ->
                // Get the dialog selected item
                val color = arrColor[which]

                // Try to parse user selected color string
                try {
                    // Change the layout background color using user selection
                    layoutRoot.setBackgroundColor(Color.parseColor(color))
                    Toast.makeText(this, "$color color selected.", Toast.LENGTH_SHORT).show()
                } catch (e: IllegalArgumentException) {
                    // Catch the color string parse exception
                    Toast.makeText(this, "$color color not supported.", Toast.LENGTH_SHORT).show()
                }
            }

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

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

Link