1

I have a grid of 6 dice on a board that I want to access as imageButtons in Android Studio. Each imagebutton has an ID (button1 is "ImageButton1", while button two is "ImageButton2" etc.). I would like to access these buttons in one for loop, rather than writing six semi-identical statements, something like shown below:

for (int i=0; i<6; i++) {
        ImageButton c+i = (ImageButton)findViewById(R.id.imageButton+i);
}

Where imageButtton1 would be stored in the variable c1, and so forth. Obviously, this for loop does not work as written. Is there a way to implement this?

Eragon20
  • 483
  • 1
  • 7
  • 20

1 Answers1

3

You can't access Java variables by name dynamically unfortunately.

But could you add them to a list as a one-off.

List<ImageButton> allButtons = new ArrayList<>() {{
    add((ImageButton) findViewById(R.id.imageButton1));
    add((ImageButton) findViewById(R.id.imageButton2));
    add((ImageButton) findViewById(R.id.imageButton3));
    // etc.
}};

So that you can simplify the rest of the code by iterating over them easily.

for (ImageButton button : allButtons) {
    ...
}

Alternatively, you could create a method to return an image button by index:

private ImageButton imageButton(int index) {
    switch (index) {
        case 1: return (ImageButton) findViewById(R.id.imageButton1);
        case 2: return (ImageButton) findViewById(R.id.imageButton2);
        case 3: return (ImageButton) findViewById(R.id.imageButton3);
        //etc.
    }
}

Although this is duplicative, it's simple and readable and all in one place—i.e. should be easy to maintain.

ᴇʟᴇvᴀтᴇ
  • 12,285
  • 4
  • 43
  • 66
  • I think he was asking how to get the instance of imageButton1 ,2 ... in a loop without doing what he is doing. – Eddie Martinez Mar 14 '17 at 18:22
  • what he was trying to do cannot be done, it is called dynamic access to variables with static names. Your code shows how to add ImageButtons to array, but he wanted to initialize them in a loop using dynamic names. – Eddie Martinez Mar 14 '17 at 18:35