我想创建警报对话框项。这是我的代码。
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()
}
}
结果,显示一个警告对话框,其中有红色,绿色和蓝色三个选择。但是问题是,如果我单击例如红色,它也会显示三个Toasts 如果我单击蓝色/绿色,则显示相同。那么如何在特定的颜色选择上显示特定的Toast?
答案 0 :(得分:1)
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()
您可以将代码放入块中。
答案 1 :(得分:0)
builder.setItems(colors) { dialog, position ->
Toast.makeText(this,colors[position],Toast.LENGTH_LONG).show()
}
您可以使用position参数来获取所需的颜色。
答案 2 :(得分:0)
Alert Dialog
提供三个按钮
1. setPositiveButton
2. setNegativeButton
3. setNeutralButton
您可以分别创建每个侦听器的一部分。
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
}