5

I want to create alert dialog items. Here is my code.

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()
    }
}

In result, an alert dialog shows with 3 selections red, green and blue. But the problem is if I click on for example red color, so it shows three Toasts also if I click the blue/green color it shows the same. So how can I show a specific Toast on specific color select?

Reza Mousavi
  • 4,420
  • 5
  • 31
  • 48

3 Answers3

2
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()

You can put the code inside the block.

Sanket Naik
  • 176
  • 2
  • 8
1
 builder.setItems(colors) { dialog, position -> 
        Toast.makeText(this,colors[position],Toast.LENGTH_LONG).show() 
    }

you can make use of the position argument to get the color you want.

Angel Koh
  • 12,479
  • 7
  • 64
  • 91
  • Thank you for your answer.It works but what if i want to do something instead of Toast. –  Sep 27 '18 at 09:41
  • just replace the toast statement with a method to do the functionality that you want to achieve. – Angel Koh Sep 28 '18 at 04:20
0

Alert Dialog provide with three buttons
1. setPositiveButton
2. setNegativeButton
3. setNeutralButton

You can create the listener part of each, individually.

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
            }
Akshay Nandwana
  • 1,260
  • 11
  • 18