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?

3
  • 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. Commented Jun 20, 2016 at 11:06
  • As per my knowledge , A Big No , you can't do this in loop Commented Jun 20, 2016 at 11:11
  • I ran in a similar issue and this helped me: stackoverflow.com/a/8008659/6470431 Commented Jun 20, 2016 at 11:14

5 Answers 5

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Load it via getResources().getIntArray()

Iterate it as usual

Comments

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.

Comments

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);
}

Comments

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.