1

I am trying to interact with dynamically generated buttons. I want to update text and background color for those player clicked and for those who is near by horizontal or vertical axis at the moment of a click.

What I've tried. I've found an id property of a button in XML which led me to idea that I can make a text key to refer to a programmatically generated button. But when I've tried to assign an id - IDE was expecting a number (Int), not a string. Since buttons form a square array - I decided to encode each button via 4 digit number where first 2 digits stand for a row number and other two stand for a column number. Though when I tried to use findViewById IDE told me that it was expecting a special id data type, not a number.

That's how it looks for now:

for (i in 1..size) {
    for (j in 1..size){
        val button = Button(this)
        button.id = i*100 + j
        constraintLayout.addView(button)
    }
}

What idea or method could I look at?

Daniel Widdis
  • 8,424
  • 13
  • 41
  • 63
  • That IDE message about the special ID data type is from lint. You should be able to suppress it. Put your cursor on the problematic line, and hit alt-enter. There should be a menu item for it. – Mike M. Nov 20 '18 at 05:02
  • if you have only your custom buttons with id you can get all the childs of coordinator layout and iterate over them. – karan Nov 20 '18 at 05:04
  • 1
    Mike, thanks! I've tryed to use **val btn = constraintLayout.findViewById(101) as Button** and via **toast** I was able to confirm it's the right button by **btn.text.toString()** – Roman Voronov Nov 20 '18 at 05:18

1 Answers1

0

If you created it dynamically you can save it in a variable (or an array) for later use.

val myButtons = ArrayList<Button>()

for (i in 1..size) {
    for (j in 1..size){
        val button = Button(this)
        myButtons.add(button)
        constraintLayout.addView(button)
    }
}

if you have a layout with dynamically created views and you know their order you can get them with getChildAt(index).

Alternatively you can assign ids saved in xml like this.

Leonardo Velozo
  • 598
  • 1
  • 6
  • 16