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

不问归期 提交于 2019-12-03 13:16:15

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

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

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.

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