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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With