Domanda

I have a function that loads a Color array that i need for alternating colors in my listview.

I load an xml array from resources, this is a stringarray so i want to convert this to a colorarray. My code is underneath:

public Color[] initColors() {
    String[] allColors = activity.getResources().getStringArray(R.array.colors);

    Color[] colors= new Color[10];
    try { 
        for(int i=0;i<allColors.length || i < 10;i++) {
            String colorstring = allColors[i];
            colors[i] = Color.parseColor(colorstring);
        }

    }catch(IndexOutOfBoundsException oob) {
        oob.printStackTrace();
    }catch(NullPointerException npe){
        //empty
        npe.printStackTrace();
    }
    return colors;

}

Now i get an red underlining and the message:

Type mismatch, cannot convert from int to Color

But i am absolutely sure colorstring is a String, so why is it saying im entering an int? The Color.parseColor function should work with a string...

Any idea? I really don't get it and have the idea that im doing this correct but eclipse isn't

È stato utile?

Soluzione 2

It is not the colorString that's giving the error, but this

colors[i] = Color.parseColor(str);
^^^^^^^^

Because the Color#parseColor returns an int and not a Color object.

Hence, the error that int(return type of parseColor()) cannot be converted to Color.

Altri suggerimenti

Color.parseColor returns an int as in java doc:

Parse the color string, and return the corresponding color-int. If the string cannot be 
parsed, throws an IllegalArgumentException exception. Supported formats are: #RRGGBB 
#AARRGGBB 'red', 'blue', 'green', 'black', 'white', 'gray', 'cyan', 'magenta', 
'yellow', 'lightgray', 'darkgray' 
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top