如何制作警报对话框项目?

How to make Alert dialog items?

我想创建警报对话框项。这是我的代码。

val colors = arrayOf("Red","Green","Blue")
        val builder = AlertDialog.Builder(this)

        builder.setTitle("Pick a color")
        builder.setItems(colors) {_,_ ->
            Toast.makeText(this,"Red Color",Toast.LENGTH_LONG).show()
            Toast.makeText(this,"Green Color",Toast.LENGTH_LONG).show()
            Toast.makeText(this,"Blue Color",Toast.LENGTH_LONG).show()
        }
        builder.show()
    }
}

结果,一个警告对话框显示了 3 个 select 离子红色、绿色和蓝色。但问题是如果我点击例如红色,那么它也会显示三个吐司 如果我单击 blue/green 颜色,它会显示相同的颜色。那么如何在特定颜色上显示特定 Toast select?

 builder.setItems(colors) { dialog, position -> 
        Toast.makeText(this,colors[position],Toast.LENGTH_LONG).show() 
    }

您可以使用位置参数来获得您想要的颜色。

Alert Dialog 提供三个按钮
1. 设置正向按钮
2. setNegativeButton
3. 设置中性按钮

您可以单独创建每个的侦听器部分。

builder.setPositiveButton("RED"){dialog, which ->
                // Do something when user press the positive button
            }

            // Display a negative button on alert dialog
builder.setNegativeButton("GREEN"){dialog,which ->
                // Do something when user press the negative button
            }

            // Display a neutral button on alert dialog
builder.setNeutralButton("BLUE"){_,_ ->
                // Do something when user press the neutral button
            }
AlertDialog.Builder(this)
                .setItems(arrayOf("RED", "GREEN", "BLUE")) { _, pos ->
                    when (pos) {
                        0 -> {
                            Toast.makeText(this@MainActivity, "Red selected", Toast.LENGTH_SHORT).show()
                        }
                        1 -> {
                            Toast.makeText(this@MainActivity, "Green selected", Toast.LENGTH_SHORT).show()
                        }
                        2 -> {
                            Toast.makeText(this@MainActivity, "Blue selected", Toast.LENGTH_SHORT).show()
                        }
                        else -> {
                            Toast.makeText(this@MainActivity, "Nothing selected", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
                .show()

您可以将代码放在块中。