Android:在创建时设置随机颜色背景

Phi*_*992 9 random android background colors oncreate

我想要的是当我加载我的应用程序时,从一个预定义的字符串列表中随机地获得某个彩色背景,这些字符串存储在名为colors的值xml文件中.

我目前拥有的是使用eclipse中的gui编辑器通过字符串颜色代码定义的背景颜色.

对于我的生活,无法弄清楚如何让背景随机选择9个字符串中的一个并在每次激活活动时显示它.

对此的指导将是非常宝贵的.

Hem*_*nth 42

在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> 
Run Code Online (Sandbox Code Playgroud)

在onCreate()

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


Mil*_*ele 5

答案要比提供的答案好得多.

如果你想要一个真正的随机颜色,从res文件中"随机"选择并不能证明它几乎是健壮的.

相反,请使用以下代码段:

  Random rnd = new Random();
    currentStrokeColor = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
Run Code Online (Sandbox Code Playgroud)