1

可能重复:
android:如何优雅地设置许多按钮 ID

这是一个用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);
4

3 回答 3

5

您可以,一种方法如下:

ImageButton[] btns = {R.id.imageButton1, R.id.imageButton2, ..., R.id.imageButton10};
for(int i = 0, len = btns.length; i < len; i++) {
    seatButton[i] = (ImageButton) findByViewId(btns[i]);
}
于 2011-09-26T18:50:42.157 回答
3

您也可以使用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);
}
于 2011-09-26T19:08:52.590 回答
0

我对您的应用程序或android一无所知,但是您可以使用运行时反射(尽管在我看来,如果可以避免它,则不应使用它)。

import java.lang.reflect.Field;

...

for(int i=1; ; i++) {
    try {
        Field f = R.id.getClass().getField("imageButton" + i);
        seatButton[i-1] = (ImageButton) findByViewId(f.get(R.id)); // Add cast to whatever type R.id.imageButton<i> is
    } catch (Exception e) {
        break;
    }
}
于 2011-09-26T19:10:03.090 回答