我想创建 2 个 ArrayList。一个有 16 种颜色,另一个有 139 种颜色。
我有颜色列表(RGB 为 255,126,32,十六进制为 0xFFFF2552)。我想使用 ArrayList 稍后从中选择随机颜色。
我试过 int[],但没用。我试过了 ArrayList<Integer>
和 ArrayList<Color>
.我的问题是;我不明白如何将颜色添加到 ArrayList。
谢谢!!
目前,我正在探索这个:
Color cBlue = new Color(0,0,255);
Color cRed = new Color(255,0,0);
ArrayList colors = new ArrayList();
colors.add(cBlue);
colors.add(cRed);
等等……
我很喜欢int[] colors = = new int[] {4,5};
因为它只有一行代码...但我如何获取颜色,以便稍后从中选择颜色?
或者.. 将颜色存储在 strings.xml 文件中然后从那里填充 ArrayList 会更好吗?如果是这样,我应该怎么做?
谢谢!!
最佳答案
你可以试试:
int[] colors = new int[] {Color.rgb(1,1,1), Color.rgb(...)};
例如,但我认为仅使用“一行”参数来决定并不是一个好主意。
List<Integer> coloras = Arrays.asList(new Integer[]{Color.rgb(1, 1, 1), Color.rgb(...)});
也可以。
您可以在arrays.xml
文件中创建一个数组列表:
<resources>
<string-array name="colors">
<item>#ff0000</item>
<item>#00ff00</item>
<item>#0000ff</item>
</string-array>
</resources>
然后使用循环读取它们:
String[] colorsTxt = getApplicationContext().getResources().getStringArray(R.array.colors);
List<Integer> colors = new ArrayList<Integer>();
for (int i = 0; i < colorsTxt.length; i++) {
int newColor = Color.parseColor(colorsTxt[i]);
colors.add(newColor);
}
在我看来,将颜色保留在列表中是最方便的解决方案。
要从列表中随机取一种颜色,您需要:
int rand = new Random().nextInt(colors.size());
Integer color = colors.get(rand);
关于java - 为 Android 用颜色填充 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27992120/