Android-使用Java循环播放ID

问题描述:

我想查找不同的TextViews,这取决于整数。Android-使用Java循环播放ID

比方说,我已经有三个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"/> 

在我MainActivity我有以下几点:

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

所以结果应该是,我能够访问不同TextViews在textCounter上,但它不起作用。

但使用此代码给我一个错误,它说findViewByID函数需要一个整数。

+2

可能重复[Android,从字符串获取资源ID?](http://stackoverflow.com/questions/4427608/android-getting-resource-id-from-string) –

您可以使用getIdentifier()转换资源ID的字符串版本。 你只需要以这种方式修改你的代码。

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