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?
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);
}
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);
}
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