Convert String to Color int

Jakob picture Jakob · Jan 5, 2013 · Viewed 7.7k times · Source
    String ColorString = "Color.BLUE";

    int colorint = Integer.parseInt(ColorString);

    ...

    views.setTextColor(R.id.tvConfigInput, colorint);

Why does this crash? in the logcat i get java.lang.numberformatexception: Invalid int "Color.BLUE"

I kinda think its at the conversion from string to int it's wrong, because if i just set the int like this:

int colorint = Color.BLUE;

it works.. but what's wrong with it i don't know.

THANKS very much

Answer

Ahmad picture Ahmad · Jan 5, 2013

The constant value of Color.Blue is: -16776961 (0xff0000ff). You are not parsing an int, your are just trying to parse a string and convert it into a int(which won't work).

"Color.BLUE" is not an Integer, but Color.BLUE will eventually return a constant value.

You need to do this in order to get it right:

int colorInt = Color.BLUE;
views.setTextColor(R.id.tvConfigInput, colorInt);

Edit:

String ColorString = "BLUE";
int colorInt = Color.parseColor(ColorString);
views.setTextColor(R.id.tvConfigInput, colorInt);