dimanche 17 novembre 2019

Android: Set Random background color for textview on create

I want is when I load my app up it to randomly have a certain colored background for each textview from a predefined list of strings.

 @Override
protected void onCreate(Bundle savedInstanceState) {

    int[] rainbow = getResources().getIntArray(R.array.rainbow);
    int randomAndroidColor = rainbow[new Random().nextInt(rainbow.length)];
    TextView lab = (TextView) findViewById(R.id.view1);
    lab.setBackgroundColor(randomAndroidColor);

colors.xml

<resources>
<color name="colorPrimary">#008577</color>
<color name="colorPrimaryDark">#00574B</color>
<color name="colorAccent">#D81B60</color>

<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>


<integer-array name="rainbow">
    <item>@color/blue</item>
    <item>@color/purple</item>
    <item>@color/green</item>
    <item>@color/orange</item>
    <item>@color/red</item>

</integer-array>

Why it does not work?




Aucun commentaire:

Enregistrer un commentaire