Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the value of R.id.ImageButton?

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
}
like image 937
masm64 Avatar asked Dec 25 '22 09:12

masm64


1 Answers

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.

like image 98
zgc7009 Avatar answered Jan 06 '23 18:01

zgc7009