所以我希望在用户输入答案时为字符串赋予随机颜色。我的问题是我不确定如何使字符串的随机颜色成为特定范围的颜色。例如,如果我想让字符串随机变成蓝色、红色、绿色、粉色、白色或棕色。只有这些颜色,没有别的。
到目前为止,我已经使用以下代码从所有可能的 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);
尽管如前所述,这不是我的目标。取而代之的是,我想要设置可以随机应用于字符串的颜色。这些是我会选择的颜色,然后随机设置为字符串颜色。这会在我不想要的范围内设置完全随机的颜色。例如,我最终可以得到 5 种蓝色变体。
如果有人能提出解决方案,我将不胜感激。谢谢。
最佳答案
首先在 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>
现在在 onCreate
方法中生成如下所示的随机颜色。
int[] androidColors = getResources().getIntArray(R.array.androidcolors);
int randomAndroidColor = androidColors[new Random().nextInt(androidColors.length)];
最后设置这个生成的颜色。
view.setBackgroundColor(randomAndroidColor);
来源取自 here .
关于java - 如何从 Java 中的一组选定颜色中输出随机颜色? (安卓),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40284802/