Skip to content Skip to sidebar Skip to footer

Changing A Buttons Background Image Through Using A Random Array

OK so I'm trying to get this button on its second click to display an image. I have 8 images for it to choose from and I want it to select it randomly. I set up an array with all o

Solution 1:

You have not really provided enough info but here is what I imagine you would do.

have an array int[] that looks like this: [R.drawable.img1, R.drawable.img2, R.drawable.img3]

in onClick(): random = some random between 0 and array.size()-1; spinntoke.setBackgroundResource(array[random]);

This way you have an array of ints (your R resources) where you can pick a random one. Don't forget to make your random generator only generate numbers from 0 to the array size-1.

Edit: code:

Random randomGenerator = new Random();
int random = randomGenerator.nextInt(array.size());
spinntoke.setBackgroundResource(array[random]);

Solution 2:

You probably want to look at drawableLeft property - or one of the others - rather than the background.

Post a Comment for "Changing A Buttons Background Image Through Using A Random Array"