Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
379 views
in Technique[技术] by (71.8m points)

java - setImageresource in android - how to use it for many pictures in a loop

it is a rather simple question. I have 5 imageViews and 5 images in drawable folder. ImageViews are named imageView1...imageView5 and images are named image1...image5

I want how can I write the following elegantly:

  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)

As you understand, there are not just 5 imageViews, but there are many more and I want to write it in a loop. I am having problems because R.drawable.imageX is integer not string.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
 //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]);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...