문제

Possible Duplicate:
android: how to elegantly set many button IDs

This is an android program made with eclipse. I've tried using string concatenation in the place of imageButton1 to no avail. R is the generated class so I cannot go into it and edit it so that the imageButtons are part of an array. How can I put this into a for loop?

    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);
도움이 되었습니까?

해결책

You can also use getResources().getIdentifier(String name, String defType, String defPackage) where name is the resource name, defType is drawable and defPackage is your full package name. Which would result in something like:

for (int i = 0; i < 10; i++) {
    int resId = getResources().getIdentifier("imageButton" + (i + 1), "id", your_package");
    seatButton[i] = (ImageButton) findViewById(resId);
}

다른 팁

You can, one approach is the following:

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]);
}

I don't know anything about your application or about android, but you could use runtime reflection (although it should not be used if you can avoid it, in my opinion).

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;
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top