Java – Iterate through multiple variables

Iterate through multiple variables… here is a solution to the problem.

Iterate through multiple variables

I have 48 variables (TextView) like tv1, tv2, tv3, tv4… tv48。

I want to set a value for these variables with a for loop because I don’t want to write the same line 48 times.

Like this:

for (int i=1; i<49; i++)
{
        "tv"+i.setText(i);
}

How to achieve this?

Solution

Initialize them like this:

TextView[] tv = new TextView[48];

You can then use for loops to set the text in it as follows:

for(int i=0; i<48; i++)
{
   tv[i].setText("your text");
}

Edit: In your XML file, provide the same ID for all TextViews. For example, tv0, tv1, tv2, etc
Initialize an array of strings, using these IDs as strings.

String ids[] = new String[48];
for(int i=0; i<48; i++)
{
   ids[i] = "tv" + Integer.toString(i);
}

Now, to initialize TextView the array of , do the following:

for(int i=0; i<48; i++)
{
   int resID = getResources().getIdentifier(ids[i], "id", "your.package.name");
   tv[i] = (TextView) findViewById(resID);
}

Related Problems and Solutions