用 Android 的颜色填充 ArrayList

Kee*_*nen 5 java arrays android arraylist colors

我想创建 2 个 ArrayList。一个持有 16 种颜色,另一个持有 139 种颜色。

我有颜色列表(RGB 为 255,126,32,十六进制为 0xFFFF2552)。我想使用 ArrayList 稍后从中选择随机颜色。

我试过 int[],这不起作用。我试过ArrayList<Integer>ArrayList<Color>。我的问题是;我不明白如何将颜色添加到 ArrayLists。

谢谢!!

现在,我正在探索这个:

Color cBlue = new Color(0,0,255);
Color cRed = new Color(255,0,0);

ArrayList colors = new ArrayList();
colors.add(cBlue);
colors.add(cRed);
Run Code Online (Sandbox Code Playgroud)

等等...

我真的很喜欢,int[] colors = = new int[] {4,5};因为它只有一行代码......但是我如何获得颜色,以便稍后从中选择?

或者..将颜色存储在strings.xml文件中然后从那里填充ArrayList会更好吗?如果是这样,我该怎么做?

谢谢!!

Pat*_*ski 6

你可以试试:

int[] colors = new int[] {Color.rgb(1,1,1), Color.rgb(...)};
Run Code Online (Sandbox Code Playgroud)

例如,但我认为仅使用“一行”参数来决定不是一个好主意。

List<Integer> coloras = Arrays.asList(new Integer[]{Color.rgb(1, 1, 1), Color.rgb(...)});
Run Code Online (Sandbox Code Playgroud)

也会工作。

您可以在arrays.xml文件中创建一个数组列表:

<resources>
    <string-array name="colors">        
        <item>#ff0000</item>
        <item>#00ff00</item>  
        <item>#0000ff</item>
    </string-array>
</resources>
Run Code Online (Sandbox Code Playgroud)

然后使用循环读取它们:

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

在我看来,将颜色保留在列表中是最方便的解决方案。

要从列表中随机选取一种颜色,您可以执行以下操作:

int rand = new Random().nextInt(colors.size());
Integer color = colors.get(rand);
Run Code Online (Sandbox Code Playgroud)