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

前端 未结 3 760
太阳男子
太阳男子 2021-02-14 23:09

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

相关标签:
3条回答
  • 2021-02-14 23:59

    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));
      }
    }
    
    0 讨论(0)
  • 2021-02-15 00:07

    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);
    
    0 讨论(0)
  • 2021-02-15 00:08

    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.

    0 讨论(0)
提交回复
热议问题