I'm making an android application, where there is a view composed of hundreds of buttons, each with a specific callback. Now, I'd like to set these callbacks using a loop, instead of having to write hundreds of lines of code (for each one of the buttons).
My question is: How can I use findViewById without statically having to type in each button id? Here is what I would like to do:
for(int i=0; i<some_value; i++) {
for(int j=0; j<some_other_value; j++) {
String buttonID = "btn" + i + "-" + j;
buttons[i][j] = ((Button) findViewById(R.id.buttonID));
buttons[i][j].setOnClickListener(this);
}
}
Thanks in advance!
Take a look at these answers:
You can try making an int[] that holds all of your button IDs, and then iterate over that:
create Custom Button in java code rather in Xml as i shown below
If for some reason you can't use the
getIdentifier()
function and/or you know the possible id's beforehand, you could use a switch.you can Use tag if you want to access.
in
onClick
But you cant access that button like this.
simply create button programatically
by
Button b=new Button(this);
If your top level view only has those button views as children, you could do
If there are more views present you'd need to check if the selected one is one of your buttons.