如何在Java中从一组选定的颜色中输出随机颜色?(安卓)

H3l*_*ll0 5 java random android colors

因此,我希望每当用户输入答案时都为字符串赋予随机颜色。我的问题是,我不确定如何使字符串的随机颜色成为特定范围的颜色。例如,如果我希望字符串随机变成蓝色、红色、绿色、粉色、白色或棕色。只有这些颜色,没有其他颜色。

到目前为止,我已经使用以下代码从所有可能的 RBG 变化中管理了完全随机的颜色:

Random rand = new Random();
            int r = rand.nextInt(254)+1;
            int g = rand.nextInt(254)+1;
            int b = rand.nextInt(254)+1;

            int randomColor = Color.rgb(r,g,b);
            word.setTextColor(randomColor);
Run Code Online (Sandbox Code Playgroud)

尽管如前所述,这不是我想要实现的目标。相反,我想要设置可以随机应用于字符串的颜色。这些是我会选择的颜色,然后随机设置为字符串颜色。这设置了一个完全随机的颜色,超出了我不打算拥有的范围。例如,我最终可能会得到 5 种不同的蓝色。

如果有人能提出解决方案,我将不胜感激。谢谢。

Aka*_*tel 6

首先在color.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)];
Run Code Online (Sandbox Code Playgroud)

最后设置这个生成的颜色。

view.setBackgroundColor(randomAndroidColor);  
Run Code Online (Sandbox Code Playgroud)

来源取自这里