android随机改变变量

时间:2015-04-25 01:55:17

标签: android

我已设置以下内容进行加载,但现在我有第二个背景图像,我想随机显示。如何来回地随机改变背景到背景?

这就是我所拥有的:

static_background_building = new Sprite(BitmapFactory.decodeResource(getResources(), R.drawable.background), ScreenWidth());

static_background_building = new Sprite(BitmapFactory.decodeResource(getResources(), R.drawable.background2), ScreenWidth());

1 个答案:

答案 0 :(得分:1)

易。只需在0和1之间设置一个随机数,然后相应地设置背景。

Random random = new Random();
int number = random.nextInt(2); // Gives a number such that 0 <= number < 2

然后:

if(number == 0)
   static_background_building = new Sprite(BitmapFactory.decodeResource(getResources(), R.drawable.background), ScreenWidth());
else
   static_background_building = new Sprite(BitmapFactory.decodeResource(getResources(), R.drawable.background2), ScreenWidth());