I'm doing an Android app that has a hundreds of button for each specific callback. Now, I want to set this loop without having to write hundreds of lines of code (one for each button). My question is: How can Findviewbyid not have static typing the ID of each button? Here's what I want 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); } }
Thank you in advance!
This address: codego.net/250944/
--------------------------------------------------------------------------------------------------------------- ----------
1. YougetIdentifier()
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", "com.sample.project"); buttons[i][j] = ((Button) findViewById(resID)); buttons[i][j].setOnClickListener(this); }}
2. Take a look at these answers: Android and get ID for casting a view as a string imagebuttons array, assigning values from a variable r.view.id
3. You can try to do an int [] that contains all the button IDs, and then the traversal is:
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. If you want to access you can use the label. The onclick INT i= in the Integer.parseint (V.gettag); But you can't access the likw that button. A simple programmatic way to create a button press the button b= a new button (this);
5. XML in Java code to create a custom button, as shown in my
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()); } }
6. If your top level view is only those buttons of the views, sub, you can do
for (int i = 0 ; i < yourView.getChildCount(); i++) { Button b = (Button) yourView.getChildAt(i); b.setOnClickListener(xxxx);}
If there are multiple views you need to check whether a button is selected for you.
http://codego.net/250944/
Android version: Use Findviewbyid () with string/in a loop