Android: Using findViewById () with string / in loop

I am making an Android application where there is a view consisting of hundreds of buttons, each of which has a specific callback. Now, I would like to set these callbacks using a loop, instead of writing hundreds of lines of code (for each of the buttons).

My question is: how can I use findViewById without static input of 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!

+56
android button clicklistener
Feb 01 '11 at 16:35
source share
7 answers

You must 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); } } 
+99
Feb 01 '11 at 16:44
source share

You can try making an int [] that contains all your button identifiers, and then repeat this:

 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); } 
+4
Feb 01 '11 at 16:39
source share

Take a look at these answers:

  • Android and getting view with id as string
  • Array from ImageButtons, assign R.view.id from the variable
+3
Feb 01 '11 at 16:40
source share

you can use the tag if you want to access.

in onClick

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

But you cannot access this button.

just create a button programmatically

Button b=new Button(this);

+1
Feb 01 '11 at 16:42
source share

create a custom button in Java code and in Xml as shown below

 Button bs_text[]= new Button[some_value]; for(int z=0;z<some_value;z++) { try { bs_text[z] = (Button) new Button(this); } catch(ArrayIndexOutOfBoundsException e) { Log.d("ArrayIndexOutOfBoundsException",e.toString()); } } 
0
Feb 01 '11 at 16:43
source share

If your top-level view has only those button representations as children, you can do

 for (int i = 0 ; i < yourView.getChildCount(); i++) { Button b = (Button) yourView.getChildAt(i); b.setOnClickListener(xxxx); } 

If there are more views, you will need to check if one of your buttons is the one you selected.

0
Feb 01 '11 at 16:55
source share

If for some reason you cannot use getIdentifier() and / or know a possible identifier in advance, you can use the switch.

 int id = 0; switch(name) { case "x": id = R.id.x; break; etc.etc. } String value = findViewById(id); 
0
Apr 17 '18 at 23:08
source share



All Articles