开发者

Changing a buttons background image through using a random array

OK so I'm trying to get this button on its second c开发者_运维知识库lick 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 of the R.drawable.img in the string and i tried placing it inside of this

   else if (click == 1)
                {
                    rpic = generator.nextInt(ppic);
                    spinntoke.setBackgroundResource(R.pic[rpic]);
                }

So it is not allowing me to do that. Any ideas as to how i can get the random generator to select 1 of those 8 pictures at random when it is clicked? Thanks


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜