Search code examples
androidrandomandroid-imagebutton

Change ImageButton Drawable automatically


I have 320 images in drawable directory and ImageButton so when it's clicked, the Image have to be changed randomly, the image name is like this file_xyz, the xyz are numbers each one generated randomly using this code:

rand = new Random(System.currentTimeMillis());
x = rand.nextInt(3 - 0) + 0;
y = rand.nextInt(7 - 0) + 0;
z = rand.nextInt(9 - 0) + 0;
return "shape_" + x+ y+ z;

so this gives me a string which I want to use it to change the resource of ImageButton, so how to apply this and make the changes randomly in separate times?


Solution

  • try this:

       int resID = getResources().getIdentifier(pDrawableName , "drawable", getPackageName());    
        imageview.setBackgroundResource(resID);
    

    where String pDrawableName = file_xyz is your image name