0

I'm trying to create an ArrayList of 11 Button widgets in my Kotlin mobile app for Android. And I want to populate the array list with 10 Button widgets using a for loop as follows.

        var buttons = ArrayList<Button>()

        // data input buttons
        for (i in 0..10) {
            buttons[i] = findViewById(R.id."button${i}")
        }

This, however, throws an error because I can't access each of my Button widgets (numbered like: button0, button1, ..., button 10) using a string literal that way.

Is there a way to do this without individually assigning each Button widget like this: ?

        val button0 : Button = findViewById(R.id.button0)
        val button1 : Button = findViewById(R.id.button1)
        val button2 : Button = findViewById(R.id.button2)
        val button3 : Button = findViewById(R.id.button3)
        val button4 : Button = findViewById(R.id.button4)
        val button5 : Button = findViewById(R.id.button5)
        val button6 : Button = findViewById(R.id.button6)
        val button7 : Button = findViewById(R.id.button7)
        val button8 : Button = findViewById(R.id.button8)
        val button9 : Button = findViewById(R.id.button9)
        val button10 : Button = findViewById(R.id.button10)

Umar Khan
  • 13
  • 4
  • While the duplicate is about drawable IDs, `R.id` values are also resources, so you should be able to look them up using an `"id"` resource type: `int buttonId=getResources().getIdentifier("button"+index, "id", getPackageName());` – CommonsWare Oct 21 '21 at 15:27

0 Answers0