Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic access to elements of the layout

Tags:

android

I have a question that is driving me crazy.

I have a large number of buttons (10, more or less) on my screen, inside a TableRow.

I need to access them, and I had planned to perform through a loop.

Access to one, is very easy, adding this:

boton7 = (Button) findViewById (R.id.Btn7)

My question is, if you can dynamically set the id string (R.id.Btn7) to put in a can get the buttons for, and for example, change the color .... something like this:

for (int i = 0; i <10; i + +) {
   Button eachBoton= (Button) findViewById (R.id.Btn + i);
   eachBoton. setBackgroundColor (Color.Red);
}

That, of course, does not work .... my question is if anyone knows how exactly the chain can be mounted

R.id.Btn + i

to work.

Thanks a lot.

like image 499
Jose Manuel Avatar asked Nov 07 '10 11:11

Jose Manuel


1 Answers

You can use Resources#getIdentifier() to get a resource identifier for the given resource name:

int resourceId = getResources().getIdentifier(
    "Btn"+i,
    "id",
    this.getContext().getPackageName());
Button button = (Button) findViewById(resourceId);

Alternately you can prepare an array with all the ids you need and access elements of that array. This is more efficient:

private final int[] btns = {R.id.btn1, R.id.btn2, R.id.btn3, R.id.btn4, ...}
...
Button button = (Button) findViewById(btns[i]);
like image 186
Alex Jasmin Avatar answered Sep 23 '22 02:09

Alex Jasmin