Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you loop through view id's?

Tags:

android

For my android app I need to make an array of View ID's.

The array will hold 81 values so it's quite lengthy to add them one by one. This is how it looks now:

cells[0] = R.id.Square00;
cells[1] = R.id.Square01;
cells[2] = R.id.Square02;
cells[3] = R.id.Square03;
cells[4] = R.id.Square04;
cells[5] = R.id.Square05;
//All the way to 80.

Is there a shorter/more efficient way of doing this?

like image 468
BBB Avatar asked Nov 24 '12 20:11

BBB


2 Answers

Thankfully, there is. Use getIdentifier():

Resources r = getResources();
String name = getPackageName();
int[] cells = new int[81];
for(int i = 0; i < 81; i++) {
    if(i < 10)
        cells[i] = r.getIdentifier("Squares0" + i, "id", name);
    else
        cells[i] = r.getIdentifier("Squares" + i, "id", name);
}
like image 196
Sam Avatar answered Oct 08 '22 04:10

Sam


Sam's answer is better but i think i should share an alternative

int [] ids = new int [] {R.id.btn1, R.id.btn2, ...};
Button [] arrayButton = new Button[ids.length];

for(int i=0 ; i < arrayButton.length ; i++)
{
  arrayButton[i] = (Button) findViewById(ids[i]);
}

Modified form of Sam Answer

No need of if else use Integer String Formating

Resources r = getResources();
String name = getPackageName();

int[] resIDs = new int[81];

for(int i = 0; i < 81; i++) 
{
        resIDs[i] = r.getIdentifier("Squares0" + String.format("%03d", i), "id", name);
}
like image 36
Zar E Ahmer Avatar answered Oct 08 '22 05:10

Zar E Ahmer