user971741
user971741

Reputation:

Retrieve elements through using variable IDs

I have number of check-boxes with their ids as per a pattern sequence. Like checkboxes1, checkboxes2, checkboxes3 etc..

I want to run a loop keeping each box, retrieve value, perform some function and move on.

Something like:

    for(int i=0;i<9;i++)
    {
        String elementId="checkboxes"+Integer.toString(i);
        CheckBox elementcb = (CheckBox) findViewById(R.id.elementId);
    }

But of course the above thing won’t work as I can’t just simple append a variable in front of R.id.. So how can I achieve the above?

Upvotes: 0

Views: 33

Answers (1)

M.Khouli
M.Khouli

Reputation: 4122

for(int i=0;i<9;i++)
{

    String elementId="checkboxes"+Integer.toString(i);

    int resID = getResources().getIdentifier(elementId,"id", getPackageName());

    CheckBox elementcb = (CheckBox) findViewById(resID);
}

hope this help :)

Upvotes: 0

Related Questions