Array of ImageButtons, assign R.view.id from a variable

这一生的挚爱 提交于 2019-12-04 18:54:28

问题


Hey there. My app is going to be using an array of 64 ImageButtons (8x8), and they're all already declared in my XML Layout with names like one1, two5, eight8, etc. Rather than declare these each individually 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 that basically create a string that will be in place of R.id.whatever. It's just that last line in my loops, that is supposed to do the assigning. What would the correct syntax for that be, or is this not even possible to do (and if so, how better would I handle a 64 button grid?). Thanks!

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

回答1:


I like AndrewKS' for, it's more elegant. Just keep in mind that findViewById receives an integer rather than a String. So you will have to do something like:

int resID = getResources().getIdentifier(btnID, "drawable", "com.your.package");
musicGrid[i][j] = (ImageButton) findViewById(resID);



回答2:


If you didn't already hardcode the buttons in the xml, I would have said to do it programmatically with a ViewInflater, but since you did here's the code:

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



回答3:


Unless there's some specific need to do it as individual ImageButtons, you might be better off using a GridView.

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



来源:https://stackoverflow.com/questions/3937010/array-of-imagebuttons-assign-r-view-id-from-a-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!