Reputation: 11829
I have 48 variables (TextViews), like tv1, tv2, tv3, tv4...tv48.
I want to set a value for these variables, with a for loop, since I do not want to write down the same row 48 times.
Something like this:
for (int i=1; i<49; i++)
{
"tv"+i.setText(i);
}
How to achieve this?
Upvotes: 4
Views: 2494
Reputation: 820
Initialize them like this:
TextView[] tv = new TextView[48];
Then you can set text in them using for
loop like this:
for(int i=0; i<48; i++)
{
tv[i].setText("your text");
}
EDIT: In your XML file, give identical IDs to all the textviews. For e.g. tv0, tv1, tv2 etc. Initialize a string array, which will have these IDs as string.
String ids[] = new String[48];
for(int i=0; i<48; i++)
{
ids[i] = "tv" + Integer.toString(i);
}
Now, to initialize the array of TextView
, do this:
for(int i=0; i<48; i++)
{
int resID = getResources().getIdentifier(ids[i], "id", "your.package.name");
tv[i] = (TextView) findViewById(resID);
}
Upvotes: 5
Reputation: 82553
TextView[] textViews = new TextView[48];
int[] ids = new int[48];
for(int i=0;i<48;i++) {
textViews[i] = (TextView) findViewById(ids[i]);
}
for(int i=0;i<48;i++) {
textViews[i].setText(String.valueOf(i));
}
Here, you will need to add all the IDs to the ids
array.
Upvotes: 2
Reputation:
"tv"+i
can be used only with Reflection.
I would put those TextViews in an array and
for (int i=0; i<textViews.length; i++)
{
textViews[i].setText(""+i);//be a String. not an int...
}
I would use, where textViews = new TextViews[]{tv1,tv2..tv48}
I hope it helps!
Upvotes: 1