Feint Feint - 5 months ago 10
Java Question

How to add to an array elements with different ids

Sorry if the title wasn't clear enought, but what I'm trying to do is this:

In the xml I have a lot of

EditText
fields with different ids but almost the same(e.g. A1, A2, A3 etc.). What I'm trying to do is to add the values from those ids in an array with a loop.

EditText[] rEdit = new EditText[25];

for (int i = 0; i < 25; i++) {
rEdit[i] = (EditText) findViewById(R.id.A1);
}


How can I do it, so it will iterate through the ids too?

Answer

Assuming your Views have their IDs like yourViewName0, yourViewName1, yourViewName2 etc.

You could do something like this:

EditText[] rEdit = new EditText[25];

for (int i = 0; i < 25; i++) {
    EditText editText = (EditText) findViewById(getResources().getIdentifier("yourViewName" + i, "id", getPackageName()));
    rEdit[i] = editText;
}
Comments