Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 353
user573536 Avatar asked Feb 01 '11 16:02

user573536


People also ask

What is findViewById () method used for?

FindViewById<T>(Int32)Finds a view that was identified by the id attribute from the XML layout resource.

How does findViewById work on Android?

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.

What is the use of findViewById in Android with example?

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'.

What does findViewById return?

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 .


1 Answers

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);    } } 
like image 117
WarrenFaith Avatar answered Sep 24 '22 14:09

WarrenFaith