Reputation: 88
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.
Upvotes: 0
Views: 82
Reputation: 81
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);
}
Upvotes: 0
Reputation: 13539
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);
}
Upvotes: 1