Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through numerous variables

Tags:

java

android

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?

like image 888
erdomester Avatar asked Feb 20 '23 03:02

erdomester


1 Answers

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);
}
like image 162
Shubham Avatar answered Feb 28 '23 08:02

Shubham