Search code examples
androidfor-loopfilenamesdrawableandroid-drawable

Different image for each round of for loop


I have images as resources and the filenames are image1, image2,... and so on. I'd like to use these images in a carousel. I can generate the same image in the carousel, but the name of the resource should change in every round of loop.

Here is the code:

    for (int i = 0; i < 4; i++) {
        ImageView imageView = new ImageView(this);
        imageView.setId(i);
        imageView.setPadding(2, 2, 2, 2);
        imageView.setLayoutParams(layoutParams);
        imageView.setImageBitmap(BitmapFactory.decodeResource(
                getResources(), R.drawable.image_01));
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        mainHorizLinLayout.addView(imageView);
    }

So instead of image_01 I'd want to use image_ + i. I tried to create a string and use that in R.drawable.image_01 but it did not work.

Any ideas, tanks?


Solution

  • R.drawable.image_01 is not a string (ALT + click to view R class). But these ints are in order so you can do:

     imageView.setImageBitmap(BitmapFactory.decodeResource(
                getResources(), R.drawable.image_01 + i));