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

1つのアプローチは次のとおりです。

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 は drawable、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

私はあなたのアプリケーションやアンドロイドについて何も知りませんが、ランタイムリフレクションを使用できます (私の意見では、回避できる場合は使用しないでください)。

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 に答える