问题
it's my code:
ImageView img1 = (ImageView) findViewById(R.id.img1);
ImageView img2 = (ImageView) findViewById(R.id.img2);
ImageView img3 = (ImageView) findViewById(R.id.img3);
ImageView img4 = (ImageView) findViewById(R.id.img4);
ImageView img5 = (ImageView) findViewById(R.id.img5);
ImageView img6 = (ImageView) findViewById(R.id.img6);
ImageView img7 = (ImageView) findViewById(R.id.img7);
ImageView img8 = (ImageView) findViewById(R.id.img8);
ImageView img9 = (ImageView) findViewById(R.id.img9);
I d like to create something like this:
for (int i=1; i<=9; i++) {
ImageView img+i = (ImageView) findViewById(R.id.img+i);}
How can I do that?
回答1:
Do It like this. You can get drawable names from array stored in xml or code.
for (int i=1; i<=9; i++) {
int id = getResources().getIdentifier("drawableName", "drawable", context.getPackageName());
ImageView img = (ImageView) findViewById(id);
}
Here "drawableName" is the name of your image and leave "drawable" as is.
回答2:
You cannot do this in the loop. Basically R.id.img is a integer and if you do R.id.img + i, it will result in some random integer.
来源:https://stackoverflow.com/questions/29560173/findviewbyid-with-for-loop