2016-07-29 39 views
0

我想查找不同的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) –

回答

0

您可以使用getIdentifier()轉換資源ID的字符串版本。 你只需要以這種方式修改你的代碼。

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