0

这是一个相当简单的问题。我在可绘制文件夹中有 5 个 imageViews 和 5 个图像。ImageViews 被命名imageView1......imageView5并且图像被命名image1......image5

我想如何优雅地编写以下内容:

  imageView1.setImageResource(R.drawable.image1)
  imageView2.setImageResource(R.drawable.image2)
  imageView3.setImageResource(R.drawable.image3)
  imageView4.setImageResource(R.drawable.image4)
  imageView5.setImageresource(R.drawable.image5)

如您所知,不仅有 5 个 imageView,而且还有更多,我想循环编写它。我遇到问题是因为R.drawable.imageX整数不是字符串。

4

1 回答 1

1
 //Declaration 

 private int[] tabDrawables = new int[] {
                    R.drawable.image1,R.drawable.image2,
                    R.drawable.image3, R.drawable.image4,
                    R.drawable.image5};



     private ArrayList<ImageView> listImages = new ArrayList<ImageView>();


    //When you find your images on the onCreate method
    //add all images here

    listImages.add(imageView1);
    listImages.add(imageView2);
        ...

    for (int i = 0; i < tabDrawables.length; i++) {
         listImages.get(i).setImageResource(tabDrawables[i]);
}
于 2012-08-27T18:39:50.910 回答