Loop through many variables

I have 48 variables (TextViews) such as tv1, tv2, tv3, tv4 ... tv48.

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

Something like that:

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

How to do it?

+4
source share
3 answers

Initialize them as follows:

 TextView[] tv = new TextView[48]; 

Then you can set the text in them using the for loop as follows:

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

EDIT: In your XML file, provide identical identifiers for all text views. E.g. tv0, tv1, tv2, etc. Initialize a string array that will have these identifiers as a string.

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

Now, to initialize the TextView array, 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); } 
+5
source
 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 identifiers to the ids array.

+2
source
 "tv"+i 

can only be used with Reflection.

I would put these TextViews into 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}

Hope this helps!

+1
source

Source: https://habr.com/ru/post/1434909/


All Articles