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

Take a look at these answers:

  • Android and getting a view with id cast as a string
  • Array of ImageButtons, assign R.view.id from a variable

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

you can Use tag if you want to access.

in onClick

int i=Integer.parseInt(v.getTag);

But you cant access that button like this.

simply create button programatically

by Button b=new Button(this);


You can try making an int[] that holds all of your button IDs, and then iterate over that:

int[] buttonIDs = new int[] {R.id.button1ID, R.id.button2ID, R.id.button3ID, ... }

for(int i=0; i<buttonIDs.length; i++) {
    Button b = (Button) findViewById(buttonIDs[i]);
    b.setOnClickListener(this);
}