Android: Set Random colour background on create

后端 未结 6 1637
既然无缘
既然无缘 2020-12-09 11:38

What I want is when I load my app up it to randomly have a certain colored background from a predefined list of strings stored in a values xml file called colours.

6条回答
  •  渐次进展
    2020-12-09 12:11

    You could set a variable Random rnd = new Random(); as a random number (will generate a psuedo-random number between 0 and 1). Then you could say:

        if (rnd < 0.09) {
            //pick first colour
        } else if (rnd >= 0.09 && rnd < 0.18) {
            //pick second colour
        } else if (rnd >= 0.18 && rnd < 0.27) {
            //pick second colour    
        } else // etc etc up to 1.0 when you will have 9 options, each with an equal chance of randomly being picked
    

    This way, the random number rnd will determine which colour the background is each time onCreate() is called.

提交回复
热议问题