用 Android 的颜色填充 ArrayList [英] Fill ArrayList with colors for Android

查看:26
本文介绍了用 Android 的颜色填充 ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to create 2 ArrayList. One holding 16 colors, the other one holding 139.

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

I have the list with colors (both RGB as 255,126,32 and Hex as 0xFFFF2552). I want to use the ArrayList to later pick random colors from.

我试过 int[],但没用.我试过 ArrayListArrayList.我的问题是;我不明白如何将颜色添加到 ArrayLists.

I've tried int[], that doesn't work. I've tried ArrayList<Integer> and ArrayList<Color>. My problem is; I don't understand how to add the colors to the ArrayLists.

谢谢!!

现在,我正在探索这个:

For now, I'm exploring this:

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}; 因为它只有一行代码...,从中挑选?

I really like int[] colors = = new int[] {4,5}; because it's only one line of code... but how do I get colors in, to later on, pick from?

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

or.. would it be better to store the colors in a strings.xml file and then fill the ArrayList from there? If so, how should I do that?

谢谢!!

推荐答案

你可以试试:

int[] colors = new int[] {Color.rgb(1,1,1), Color.rgb(...)};

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

For example, but I don't think it's a good idea to decide only using "one line" argument.

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

也能用.

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

You can create an arraylist in arrays.xml file:

<resources>
    <string-array name="colors">        
        <item>#ff0000</item>
        <item>#00ff00</item>  
        <item>#0000ff</item>
    </string-array>
</resources>

然后使用循环读取它们:

Then use the loop to read them:

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);
}

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

In my opinion keeping colors in the list is the most convinient solution.

要从列表中随机选取一种颜色,您可以:

To take a color from the list randomly, you do:

int rand = new Random().nextInt(colors.size());
Integer color = colors.get(rand);

这篇关于用 Android 的颜色填充 ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆