-6

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?

2 Answers2

3

try this:

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

where String pDrawableName = file_xyz is your image name

rafsanahmad007
  • 23,683
  • 6
  • 47
  • 62
1

If you first create the exact filename string as in the drawable folder (I'll call it String image), you can do the following:

ImageButton imageButton = (ImageButton) findViewById(R.id.image_button);
imageButton.setImageResource(R.drawable.image);

Where image_button is whatever you have set as the ID for your image button.

Anna Vos
  • 62
  • 1
  • 9
  • Have you checked whether the image name generated exactly matches the image name in your drawable folder? – Anna Vos Jan 13 '17 at 21:57