简体   繁体   中英

Android change background dynamically randomly from array

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.

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]) );

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM