Android: Set Random colour background on create

Phil3992 picture Phil3992 · Sep 19, 2014 · Viewed 23.1k times · Source

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.

Answer

Hemanth picture Hemanth · Sep 19, 2014

In colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <item name="blue" type="color">#FF33B5E5</item>
    <item name="purple" type="color">#FFAA66CC</item>
    <item name="green" type="color">#FF99CC00</item>
    <item name="orange" type="color">#FFFFBB33</item>
    <item name="red" type="color">#FFFF4444</item>
    <item name="darkblue" type="color">#FF0099CC</item>
    <item name="darkpurple" type="color">#FF9933CC</item>
    <item name="darkgreen" type="color">#FF669900</item>
    <item name="darkorange" type="color">#FFFF8800</item>
    <item name="darkred" type="color">#FFCC0000</item>

    <integer-array name="androidcolors">
        <item>@color/blue</item>
        <item>@color/purple</item>
        <item>@color/green</item>
        <item>@color/orange</item>
        <item>@color/red</item>
        <item>@color/darkblue</item>
        <item>@color/darkpurple</item>
        <item>@color/darkgreen</item>
        <item>@color/darkorange</item>
        <item>@color/darkred</item>
    </integer-array>

</resources> 

In onCreate()

int[] androidColors = getResources().getIntArray(R.array.androidcolors);
int randomAndroidColor = androidColors[new Random().nextInt(androidColors.length)];
view.setBackgroundColor(randomAndroidColor);