Search code examples
androidimageviewandroid-resourcesimagesource

How to set imageview resource based on value of integer variable. Int= X //R.drawable.imageX


I would like to know,how to dynamicly set source of imageview. I have 150 images (d1,d2,d3.......,d150) and I have integer variable "DungeonLevel", that through some time changes from 1 to 150. And I dont know how to write it. When I tried to find it, it wasnt the same or I didnt get it. So sorry if you think its duplicate.


Solution

  • int X;
    String imageName = "image" + X;
    String uriOfImage = "@drawable/" + imageName;
    int imageResource = getResources().getIdentifier(uriOfImage, null, getPackageName());
    Drawable resourceDrawable = getResources().getDrawable(imageResource);
    imageView.setImageDrawable(resourceDrawable);
    

    Here X stands for your DungeonLevel which is between 1 to 150.