0

I am new to Android and I am trying to change the background of an ImageView in Java. This part is working. The problem is I have a 4 images and I would like to randomly choose one and display the image.

For example I have an array of drawables as such:

String[] images = new String[4];
images[0] = "R.drawable.i1";
images[1] = "R.drawable.i2";
images[2] = "R.drawable.i3";
images[3] = "R.drawable.i4";

I was trying to use this to choose a random one:

int idx = new Random().nextInt(images.length);
String random = (images[idx]);

However, I cannot seem to get the setBackground for the imageview to work with these.

For example, I tried:

images.setBackgroundDrawable( getResources().getDrawable(R.drawable.images[random]) );

I know I am not doing it correctly however that is what I would like to do.

halfer
  • 19,824
  • 17
  • 99
  • 186
L1ghtk3ira
  • 3,021
  • 6
  • 31
  • 70
  • 1
    This will help: http://stackoverflow.com/questions/12523005/how-set-background-drawable-programmatically-in-android – P. Jairaj Jan 25 '16 at 13:20

2 Answers2

1

You can try this:

    int[] images = new int[4];
    images[0] = R.drawable.i1;
    images[1] = R.drawable.i2;
    images[2] = R.drawable.i3;
    images[3] = R.drawable.i4;

    int idx = new Random().nextInt(images.length);
    int random = (images[idx]);
    images.setBackgroundDrawable( getResources().getDrawable(images[random]) );
Cbibejs
  • 91
  • 4
0

Your problem seems to be, that you want to call a Method through a String. Thats absolutly nonesense unless you work with java SQL calls or XML...whatever. you need the actual image Object if you call your draw method.

well there is a simple solution :D Instead of using an String[]. Use a ArrayList<Image> after that you can call the method list.shuffle().

some pseudo Code:

ArrayList<Image> yourImages = new Arraylist<>();
yourImages[1] = image1
yourImages[2] = image2
...

yourImages.shuffle(); //shuffles your list

print(yourImages[1]);
print(yourImages[2]);
...

the first advatage is that your pictures will be displayed at random. the second advantage is that there is no duplicate of each displayed picture.

PS: It would also work with an Image[] + the Random class. But how come, choose a String[]. a String is a representation of an Text... not an image.

Tom Wellbrock
  • 2,982
  • 1
  • 13
  • 21