使用for循环为多个图像视图设置图像资源

时间:2012-03-07 22:51:36

标签: java android resources drawable

我正在尝试使用for循环为多个图像视图设置图像资源。我知道我提出的解决方案不会工作,我知道为什么。我的问题是我可以使用什么而不是这个?只是为了清楚说明,只有部分图像会根据areasArray包含的内容进行更新。例如4,7,9这意味着只有图像iv_4,iv_7,iv_9。

        iv_0 = (ImageView) ViewLameness.findViewById(R.id.iv_0);
    iv_1 = (ImageView) ViewLameness.findViewById(R.id.iv_1);
    iv_2 = (ImageView) ViewLameness.findViewById(R.id.iv_2);
    iv_3 = (ImageView) ViewLameness.findViewById(R.id.iv_3);
    iv_4 = (ImageView) ViewLameness.findViewById(R.id.iv_4);
    iv_5 = (ImageView) ViewLameness.findViewById(R.id.iv_5);
    iv_6 = (ImageView) ViewLameness.findViewById(R.id.iv_6);
    iv_7 = (ImageView) ViewLameness.findViewById(R.id.iv_7);
    iv_8 = (ImageView) ViewLameness.findViewById(R.id.iv_8);
    iv_9 = (ImageView) ViewLameness.findViewById(R.id.iv_9);
    iv_10 = (ImageView) ViewLameness.findViewById(R.id.iv_10);
    iv_11 = (ImageView) ViewLameness.findViewById(R.id.iv_11);
    iv_12 = (ImageView) ViewLameness.findViewById(R.id.iv_12);
    iv_13 = (ImageView) ViewLameness.findViewById(R.id.iv_13);

    for (int i = 0; i < areasArray.length; i++) {

        int[] images = { R.drawable.f0sc, R.drawable.f1sc, R.drawable.f2sc,
                R.drawable.f3sc, R.drawable.f4sc, R.drawable.f5sc,
                R.drawable.f6sc, R.drawable.f7sc, R.drawable.f8sc,
                R.drawable.f9sc, R.drawable.f10sc, R.drawable.f11sc,
                R.drawable.f12sc, R.drawable.f13sc };

        String image = "iv_" + areasArray[i];

        image.setImageResource(images[i]);

    }

1 个答案:

答案 0 :(得分:3)

这应该有用..

ImageView[] images = new ImageView[] { iv_1, iv_2, ... };
int[] res = new int[] { R.id.iv_1, R.id.iv_2, ... };
int[] drawables = new int[] { R.drawable.f0sc, R.drawable.f1sc, ... };
for (int i = 0; i < images.length; i++) {
    images[i] = (ImageView) findViewById(res[i]);
    images[i].setImageResource(drawables[i]);
}