2012-05-16 38 views
1

我想嘗試並將其放入一個循環,但我似乎無法使R.id.imageView匹配。我試過:string id =「R.id.imageView」+我在for循環中,但它不匹配findViewById的參數。有任何想法嗎?非常感謝任何幫助。FindViewById Loop

buttons[0] = (ImageView) this.findViewById(R.id.imageView1); 
    buttons[1] = (ImageView) this.findViewById(R.id.imageView2); 
    buttons[2] = (ImageView) this.findViewById(R.id.imageView3); 
    buttons[3] = (ImageView) this.findViewById(R.id.imageView4); 
    buttons[4] = (ImageView) this.findViewById(R.id.imageView5); 
    buttons[5] = (ImageView) this.findViewById(R.id.imageView6); 
    buttons[6] = (ImageView) this.findViewById(R.id.imageView7); 
    buttons[7] = (ImageView) this.findViewById(R.id.imageView8); 
    buttons[8] = (ImageView) this.findViewById(R.id.imageView9); 
    buttons[9] = (ImageView) this.findViewById(R.id.imageView10); 
    buttons[10] = (ImageView) this.findViewById(R.id.imageView11); 
    buttons[11] = (ImageView) this.findViewById(R.id.imageView12); 

回答

3

舉一個整數陣列,用於R.id.imageView1 ...... 12,並通過它的值 喜歡

private Integer[] Imgid = {R.id.imageview1,....,12 }; 

和使用陣列

3

使用getIdentifier()方法:

Resources res = getResources(); //if you are in an activity 
for (int i = 1; i < 13; i++) { 
    String idName = "imageView" + i; 
    buttons[i] = (ImageView) findViewById(res.getIdentifier(idName, "id, getPackageName())); 
} 
1

與上面相同,只是錯字固定。似乎比'最佳答案'更好,因爲如果你不需要它,你不必定義任何數組。

Resources res = getResources(); //if you are in an activity 
for (int i = 1; i < 13; i++) { 
    String idName = "imageView" + i; 
    imageViews[i] = (ImageView) findViewById(res.getIdentifier(idName, "id", getPackageName())); 
}