Reputation: 47
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?
Upvotes: 3
Views: 146
Reputation: 19427
Assuming your View
s 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;
}
Upvotes: 2
Reputation: 23665
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);
}
Upvotes: 0
Reputation: 505
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);
}
Upvotes: 0
Reputation: 3268
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);
}
resId
will get the A1, A2, A3...A24 ids and you can get the EditText easily as you wanted to.
Upvotes: 0
Reputation: 3804
Create an array of id's in res/values/arrays.
Load it via getResources().getIntArray()
Iterate it as usual
Upvotes: 0