I have sixteen image buttons, so I create an array of Image Buttons. I would like to initialize them with a for loop, I would not like to do that one by one, though I do not know if it is possible. For one imagebutton, it would be something, like this:
imgbtn[0] = (ImageButton)findViewById(R.id.imgButton1);
I see that the R.id.smth part is an integer. Does it say somewhere, where does that integer value start for imgButtons? So that I could so something like this:
int value = R.id.imgButton1;
for(int i = 0; i < imgbtn.length; i++)
{
imgbtn[i] = (ImageButton)findViewById(value);
value++; //or something along these lines
}
ID's aren't assigned incrementally, and are in fact quite random, so it is impossible to guess at what the resource id will be. What you need is to actually get the id dynamically via the getIdentifier() method
int value = 1;
for(int i = 0; i < imgbtn.length; i++){
int resId = getResources().getIdentifier("imgButton" + value, "id", this.getPackageName());
imgbtn[0] = (ImageButton) findViewById(resId);
value++;
}
The getResources().getIdentifier(tag, type, package) will return the actual int value stored in your resources (R) for your images. You can use that to find your views dynamically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With