0

I wanted to find different TextViews, which are depending on an integer.

Let's say I have got three TextViews:

<TextView
 android:id="@+id/text1" 
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"/>

<TextView
 android:id="@+id/text2" 
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"/>

<TextView
 android:id="@+id/text3" 
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"/>

And in my MainActivity I have got following:

String resourceText = "R.id.text";
int textCounter = 1;
TextView text1 = (TextView) findViewById(resourceText + textCounter);

So the result should be that I am able to access different TextViews over the textCounter but it doesn't work.

But using this code gives me an error which says that the findViewByID function expects an integer.

Amit Vaghela
  • 22,772
  • 22
  • 86
  • 142
  • 2
    Possible duplicate of [Android, getting resource ID from string?](http://stackoverflow.com/questions/4427608/android-getting-resource-id-from-string) – Mike M. Jul 29 '16 at 23:56

1 Answers1

0

You can use getIdentifier() to convert string version of a resource id . You just need to modify your code in this way.

String resourceText = "R.id.text";
int textCounter = 1;
textViewResId=getResources().getIdentifier(resourceText+textCounter, "id", getPackageName());
TextView text1 = (TextView) findViewById(textViewResId);
Dentor
  • 590
  • 2
  • 15