"findViewById";与for循环 [英] "findViewById" with for loop
本文介绍了"findViewById";与for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的代码:
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);}
我该怎么办?
推荐答案
做到这一点.您可以从存储在xml或代码中的数组中获取可绘制的名称.
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);
}
"drawableName"是图片的名称,请保留"drawable".
Here "drawableName" is the name of your image and leave "drawable" as is.
这篇关于"findViewById";与for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文