Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Set Random colour background on create

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.

What I currently have is one colour set as the background defined through the string colour code using the gui editor in eclipse.

For the life of me can't work out how to get the background to randomly pick one of the 9 strings and display it each time the activity is activated.

Guidance on this would be invaluable.

like image 854
Phil3992 Avatar asked Sep 18 '14 22:09

Phil3992


People also ask

How do you get random colors to flutter?

Using Colors. The Random class comes with a method name nextInt that can generate a random integer in the range from 0, inclusive, to a given max value, exclusive. You can make a random color like this: Color _randomColor = Colors. primaries[Random().


1 Answers

I think I could find an easy approach but some how long to implement ,you choose random color from a defined array of colors and than parse that string color to your background.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="bright_pink">#FF007F</color>
    <color name="red">#FF0000</color>
    <color name="orange">#FF7F00</color>
    <color name="yellow">#FFFF00</color>
    <color name="chartreuse">#7FFF00</color>
    <color name="green">#00FF00</color>
    <color name="spring_green">#00FF7F</color>
    <color name="cyan">#00FFFF</color>
    <color name="azure">#007FFF</color>
    <color name="blue">#0000FF</color>
    <color name="violet">#7F00FF</color>
    <color name="magenta">#FF00FF</color>
<array name="rainbow">
    <item>@color/bright_pink</item>
    <item>@color/red</item>
    <item>@color/orange</item>
    <item>@color/yellow</item>
    <item>@color/chartreuse</item>
    <item>@color/green</item>
    <item>@color/spring_green</item>
    <item>@color/cyan</item>
    <item>@color/azure</item>
    <item>@color/blue</item>
    <item>@color/violet</item>
    <item>@color/magenta</item>
</array>

and than this java code

String[] array = context.getResources().getStringArray(R.array.animals_array);
String randomStr = array[new Random().nextInt(array.length)];

//here you define your layout `

LinearLayout myLayout = (LinearLayout) findViewById(R.id.that_linear);

myLayout.setBackgroundColor(Color.parseColor(randomStr));
like image 107
Kiloreux Avatar answered Sep 29 '22 21:09

Kiloreux