Possible Duplicate:
android: how to elegantly set many button IDs
这是用eclipse制作的android程序。我试过使用字符串连接代替imageButton1无济于事。 R是生成的类,因此我无法对其进行编辑,因此imageButtons是数组的一部分。
如何将其放入for循环?
seatButton[0] = (ImageButton) findViewById(R.id.imageButton1);
seatButton[1] = (ImageButton) findViewById(R.id.imageButton2);
seatButton[2] = (ImageButton) findViewById(R.id.imageButton3);
seatButton[3] = (ImageButton) findViewById(R.id.imageButton4);
seatButton[4] = (ImageButton) findViewById(R.id.imageButton5);
seatButton[5] = (ImageButton) findViewById(R.id.imageButton6);
seatButton[6] = (ImageButton) findViewById(R.id.imageButton7);
seatButton[7] = (ImageButton) findViewById(R.id.imageButton8);
seatButton[8] = (ImageButton) findViewById(R.id.imageButton9);
seatButton[9] = (ImageButton) findViewById(R.id.imageButton10);
最佳答案
您也可以使用getResources().getIdentifier(String name, String defType, String defPackage)
,其中name是资源名称,defType是可绘制的,defPackage是您的完整软件包名称。
这将导致类似:
for (int i = 0; i < 10; i++) {
int resId = getResources().getIdentifier("imageButton" + (i + 1), "id", your_package");
seatButton[i] = (ImageButton) findViewById(resId);
}