3

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?

earthw0rmjim
  • 19,027
  • 9
  • 49
  • 63
Feint
  • 47
  • 6
  • 1
    As a suggestion, I would recommend removing the `android-studio` tag. This is a problem with your code and not with the IDE so you would have this problem no matter what IDE you are using. – Lexi Jun 20 '16 at 11:06
  • As per my knowledge , A Big No , you can't do this in loop – Khizar Hayat Jun 20 '16 at 11:11
  • I ran in a similar issue and this helped me: http://stackoverflow.com/a/8008659/6470431 – Westside Tony Jun 20 '16 at 11:14

5 Answers5

2

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;
}
earthw0rmjim
  • 19,027
  • 9
  • 49
  • 63
0

Create an array of id's in res/values/arrays.

Load it via getResources().getIntArray()

Iterate it as usual

Evgeniy Mishustin
  • 3,343
  • 3
  • 42
  • 81
0

Try doing this:

EditText[] rEdit = new EditText[25];

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

resIdwill get the A1, A2, A3...A24 ids and you can get the EditText easily as you wanted to.

Renan Bandeira
  • 3,238
  • 17
  • 27
0

Can you try this for the same.

EditText[] rEdit = new EditText[25];
for (int i = 0; i < 25; i++) {
String edtvId="A"+i;
int resID = getResources().getIdentifier(edtvId, "id",  "your_package_name");
 rEdit[i] = (EditText) findViewById(resID);
}
Haroon
  • 497
  • 4
  • 13
0

You can create an array with the ids first and then iterate over it:

int [] ids = new int[] {R.id.A1, R.id.A2, R.id.R3};

int n = 0;
for (int id : ids) {
    rEdit[n++] = (EditText)findViewById(id);
}
Ridcully
  • 23,362
  • 7
  • 71
  • 86