1

I have a user interface with multiple buttons. They have the IDs "button1", "button2", ... I want to set an OnClickListener for all of them in a for loop. I dont want to type a line like button1.setOnClickListener for every button.

I have found one solution that works in java here: Android: Using findViewById() with a string / in a loop And I tried to adapt it in Kotlin.

var buttons = ArrayList<Button>()
for (i in 1..7) {
    var idString = "Button%i"
    var buttonID = getResources().getIdentifier(idString, "id", packageName)
    buttons.add( findViewWithTag(buttonID))
    buttons[i].setOnClickListener(buttonclicked)
}

This throws an "Unresolved Reference" error. How can I access all buttons without typing a line for each of them? Thanks in advance to all of you.

Flostian
  • 93
  • 1
  • 7

1 Answers1

1

You call findViewWithTag() instead of findViewById() in your code.
Also you are not doing string interpolation correctly by var idString = "Button%i".
Change to this:

val buttons = ArrayList<Button>()
for (i in 1..7) {
    val idString = "Button$i"
    val buttonID = resources.getIdentifier(idString, "id", packageName)
    buttons.add(findViewById(buttonID))
    buttons[i].setOnClickListener(buttonclicked)
}
forpas
  • 160,666
  • 10
  • 38
  • 76