在colors.xml
中我有这个Array
:
<item name="purple" type="color">#FFAA66CC</item>
<item name="red" type="color">#FFFF4444</item>
<item name="darkpurple" type="color">#FF9933CC</item>
<item name="darkred" type="color">#FFCC0000</item>
<integer-array name="androidcolors">
<item>@color/purple</item>
<item>@color/red</item>
<item>@color/darkpurple</item>
<item>@color/darkred</item>
</integer-array>
我生成随机颜色,
int[] androidColors = getResources().getIntArray(R.array.androidcolors);
int randomAndroidColor = androidColors[new Random().nextInt(androidColors.length)];
button1.setBackgroundColor(randomAndroidColor);
效果很好,但有时会生成与上次相同的结果。我该如何解决这个问题?
最佳答案
首先,不要每次需要新颜色时都创建一个new Random()
,这不仅计算量大,而且完全破坏了Random
类的分布属性!只需创建一个 Random
的static
实例并重用它即可。
现在回答你的实际问题。您需要记住您生成的最后一个值,这样就可以避免重复它。创建您正在使用的类的静态变量或实例变量。我们将其命名为 lastColorIndex
,并将其初始化为随机选择的颜色。
static Random rnd = new Random();
static int lastColorIndex = rnd.nextInt(androidColors.length);
要生成不重复的颜色,您现在可以执行以下操作:
int randomColorIndex = rnd.nextInt(androidColors.length - 1);
if (randomColorIndex >= lastColorIndex) {
++randomColorIndex;
}
lastColorIndex = randomColorIndex;
button1.setBackgroundColor(androidColors[randomColorIndex]);
要生成randomColorIndex
,您的选择比颜色数量少一种,因为您最后使用的一种已被排除。如果生成的索引大于或等于最后使用的索引,则将其递增。这会导致结果均匀分布在整个索引范围内,不包括 lastColorIndex
。
关于java - 如何生成与上次不同的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41523163/