0

Is there a way, rather than individually, to use an Array to define 10 buttons and their associated images, which I have in the res folder?

I have 10 buttons already created in my xml.

I have 10 custom button images in my resource folder.

Images are named my_button_0, my_button_1, ... and so on.

For example:

for (int a = 0; a < 10; a++){
    String z = "my_button_" + Integer.toString(a);
    Button z = findViewById(R.id.z);
    z.setBackgroundResource(R.drawable.z);
}

Found several related questions, but not like this. Thanks.

1
  • In Java and Kotlin, you won't be able to have two variables with the same name (in your case: "z") in one scope. If this is essential to your question, the answer has to be "there is no way" Commented Nov 1, 2018 at 20:46

2 Answers 2

1

Suppose buttons id are named button1,button2...., you could do like this:

 for (int i = 1; i <= 10; i++) {
     int btnId = getResources().getIdentifier("button" + i, "id", this.getPackageName());
     Button btn = findViewById(btnId);
     int drawableId = getResources().getIdentifier("my_button_"+i, "drawable", getPackageName());
     btn.setBackgroundResource(drawableId);
 }
Sign up to request clarification or add additional context in comments.

1 Comment

Fantastic 'navylover'! That does indeed work. So now I can create an array of buttons, and adjust their images programmatically without having to do them individually. Thanks. Much appreciated.
0

Unfortunately there is no way as you mentioned. You can do something like this:

private int getButtonId(int i) {
    switch (i) {
        case 0:
            return R.id.my_button_1;
        case 1:
            return R.id.my_button_2;
        case 2:
            return R.id.my_button_3;
        case 3:
            return R.id.my_button_4;
        case 4:
            return R.id.my_button_5;
        case 5:
            return R.id.my_button_6;
        case 6:
            return R.id.my_button_7;
        case 7:
            return R.id.my_button_8;
        case 8:
            return R.id.my_button_9;
        case 9:
            return R.id.my_button_10;
    }
}

// in your method

for (int a = 0; a < 10; a++){
   Button z = findViewById(getButtonId(a));
   z.setBackgroundResource(R.drawable.z); 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.