“findViewById” with for loop [duplicate]

百般思念 提交于 2019-12-11 20:34:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!