Array from ImageButtons, set R.view.id from variable

Hey there. My application will use an array of 64 ImageButtons (8x8), and all of them are already declared in my XML layout with names like one1, two5, eight8, etc. Instead of declaring them each separately in my Java, I thought it might be smart to declare them all in some for loops. I have

ImageButton musicGrid[][] = new ImageButton [8][8]; 

Then I have my nested for loops, which basically create a string that will be instead of R.id.whatever. This is only the last line in my loops that should do the assignment. What will be the correct syntax for this, or is it impossible to do at all (and if so, how much better will I handle a grid with 64 buttons?). Thank!

 for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { String btnID = "R.id."; switch(i) { case 0: btnID.concat("one"); break; case 1: btnID.concat("two"); break; case 2: btnID.concat("three"); break; case 3: btnID.concat("four"); break; case 4: btnID.concat("five"); break; case 5: btnID.concat("six"); break; case 6: btnID.concat("seven"); break; case 7: btnID.concat("eight"); break; } switch(j) { case 0: btnID.concat("1"); break; case 1: btnID.concat("2"); break; case 2: btnID.concat("3"); break; case 3: btnID.concat("4"); break; case 4: btnID.concat("5"); break; case 5: btnID.concat("6"); break; case 6: btnID.concat("7"); break; case 7: btnID.concat("8"); break; } musicGrid[i][j] = (ImageButton) findViewById(btnID); } } 
+8
android arrays imagebutton
Oct. 14 '10 at 19:57
source share
3 answers

I like AndrewKS ' for , it's more elegant. Just keep in mind that findViewById gets an integer, not a string. So you will need to do something like:

 int resID = getResources().getIdentifier(btnID, "drawable", "com.your.package"); musicGrid[i][j] = (ImageButton) findViewById(resID); 
+8
Oct 14 '10 at 20:05
source share

If you haven't hard-pressed the buttons in xml yet, I would say to do it programmatically with ViewInflater, but since you made the code here:

 String[] number_as_word = ["one", "two", "three", "four", "five", "six", "seven", "eight"]; for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { musicGrid[i][j] = (ImageButton) findViewById("R.id." + number_as_word[i] + (j+1)); } } 
+2
Oct 14 '10 at 20:02
source share

Unless there is a specific need to do this as separate ImageButtons, you might be better off using a GridView .

Here is a tutorial using images in a GridView using an adapter.

0
Oct 14 '10 at 20:19
source share



All Articles