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!
FindViewById<T>(Int32)Finds a view that was identified by the id attribute from the XML layout resource.
In the case of an Activity , findViewById starts the search from the content view (set with setContentView ) of the activity which is the view hierarchy inflated from the layout resource. So the View inflated from R. layout.
findViewById is the method that finds the View by the ID it is given. So findViewById(R. id. myName) finds the View with name 'myName'.
findViewById returns an instance of View , which is then cast to the target class. All good so far. To setup the view, findViewById constructs an AttributeSet from the parameters in the associated XML declaration which it passes to the constructor of View . We then cast the View instance to Button .
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With