Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill ArrayList with colors for Android

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

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.

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.

Thanks!!

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

and so on...

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?

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?

Thanks!!

like image 531
Kees Koenen Avatar asked Jan 16 '15 20:01

Kees Koenen


People also ask

How do you add color to an ArrayList?

Color cBlue = new Color(0,0,255); Color cRed = new Color(255,0,0); ArrayList colors = new ArrayList(); colors.

How to make ArrayList of colors java?

We can easily create an ArrayList using the following statement ArrayList<String> colorList = new ArrayList<>( ); where: “colorList” is the name of the ArrayList and “ArrayList” is a class that we have to import from the “java. util” package.

What is int color in Android?

An Android color is a 32-bit integer value consisting of four eight bit parts (4x8=32). The four parts are tagged ARGB. This is the amount of Red, Green and Blue in the color, plus how opaque (see through) it is, called the Alpha value, the lower the alpha value the more transparent the color appears.

What color is int?

green(int) to extract the green component.


1 Answers

You could try:

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

Will also work.

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);
like image 156
Patryk Dobrowolski Avatar answered Sep 28 '22 18:09

Patryk Dobrowolski