Android: Using findViewById() with a string / in a loop

You should use getIdentifier()

for(int i=0; i<some_value; i++) {
   for(int j=0; j<some_other_value; j++) {
    String buttonID = "btn" + i + "-" + j;
    int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
    buttons[i][j] = ((Button) findViewById(resID));
    buttons[i][j].setOnClickListener(this);
   }
}

Leave a Comment