Convert hex color value ( #ffffff ) to integer value
Asked Answered
C

10

112

I am receiving hex color values from a server (in this form, #xxxxxx , example #000000 for black)

How do I convert this to an integer value?

I tried doing Integer.valueOf("0x" + passedColor.substring(1, passedColor.length())) to get an even more hextastic 0x000000 result, but this isn't intepreted as an int here, any other suggestions?

I receive an error: 08-03 21:06:24.673: ERROR/AndroidRuntime(20231): java.lang.NumberFormatException: unable to parse '0x00C8FBFE' as integer

I am using the Android SDK for their setBackgroundColor(int color) function, which takes - as you might have guessed - an integer color value.

This is the OPPOSITE of this question: How to convert a color integer to a hex String in Android?

Colonist answered 4/8, 2011 at 1:0 Comment(2)
As for some reason I am unable to post... You're almost there, but you need the two-argument valueOf method, where you specify the string input (without the #, of course) and the radix, which specifies the base. Integer.valueOf(passedColor.substring(1, passedColor.length()), 16) This can be done with any integer base! download.oracle.com/javase/6/docs/api/java/lang/…, int)Focalize
Possible duplicate of How to get a Color from hexadecimal Color StringSpencerianism
C
219

The real answer is to use:

Color.parseColor(myPassedColor) in Android, myPassedColor being the hex value like #000 or #000000 or #00000000.

However, this function does not support shorthand hex values such as #000.

Colonist answered 26/1, 2013 at 2:48 Comment(3)
Unfortunately in does not parse value like #000. See documentationAssonance
@Colonist how to parse shorthand hex color, like #ccc. Is there any other way?Minaminabe
@KavitaPatil I haven't tested but it seems like your utility function could detect shorthand notation and then convert by duplicating each hex digit before passing to parseColor. See here: en.wikipedia.org/wiki/Web_colors#Shorthand_hexadecimal_formSforza
B
50

Answer is really simple guys, in android if you want to convert hex color in to int, just use android Color class, example shown as below

this is for light gray color

Color.parseColor("#a8a8a8");

Thats it and you will get your result.

Blubbery answered 16/6, 2017 at 6:22 Comment(1)
And just make it clear on how to use: someText.setTextColor(Color.parseColor("#f9e6ff") )Recension
C
17
long color = Long.parseLong(colorString.substring(1), 16);
if (colorString.length() == 7) {
    // Set the alpha value
    color |= 0x00000000ff000000;
} else if (colorString.length() != 9) {
    throw new IllegalArgumentException("Unknown color");
}
return (int)color;
Cede answered 4/8, 2011 at 1:7 Comment(7)
thanks for the suggestion, I tried this just now to no avail, and it turns out an included Android function was the only kind of color result that works, even though they both return int. Color.parseColor(myPassedColor)) I didn't think this was an android specific problem, but turns out it wasColonist
I don't know why people upvoted this; it doesn't work!! The colors here are being stored in 32 bits so printing them makes them display as longs. parseInt looks for an explicit `-' to denote a negative, and doesn't respect the sign bit for ints or longs. Thus it will give the wrong number.Seesaw
@enthdegree, To quote the OP, "I am receiving hex color values from a server (in this form, #xxxxxx" so the colors the OP deals with are 24 bits not 32 bits; there is no alpha channel.Cede
@AllDayAmazing, '#' is not a hex digit, sign, or decimal separator so parseInt will fail if it finds it on the input.Cede
My mistake, I'm so ingrained in what I'm doing that I read it quickly and saw parseColor(). You are very correct.Missilery
This above solution works like a charm!! You can also convert it the other way back to the hex value using the below function where intColor is the result of the above function: val hexColor = String.format("#%06X", 0xFFFFFF and intColor)Romulus
This solution doesn't work at all and I wish the accepted answer was sorted above it. If you convert #336633 to Integer.parseInt(myString.replaceFirst("#", ""), 16) = 3368499 but Color.parseColor(myString) = -13408717. The Integer solution isn't taking into account the extra transparency values that need to be appended at the end, and therefore it needs to be Long.parseLong.Unsearchable
E
8

I have the same problem that I found some color in form of #AAAAAA and I want to conver that into a form that android could make use of. I found that you can just use 0xFFAAAAAA so that android could automatically tell the color. Notice the first FF is telling alpha value. Hope it helps

Eade answered 26/7, 2012 at 1:1 Comment(0)
T
5

The real answer is this simplest and easiest ....

String white = "#ffffff";
int whiteInt = Color.parseColor(white);
Transpontine answered 14/12, 2016 at 5:56 Comment(0)
S
4

if you can pass the values as static const, you can convert the hex value to an Android (android.graphics.Color) using this online converter and put the color reference in the const, ie: color converter give me this value for this color #EE5670 = 0xFFEE5670.

static const Color redColor = const Color(0xFFEE5670);

https://convertingcolors.com/hex-color-EE5670.html?search=#EE5670

Sauers answered 10/5, 2021 at 18:27 Comment(0)
S
3

I was facing the same problem. This way I was able to solved it. As CQM said, using Color.parseColor() is a good solution to this issue.

Here is the code I used:

this.Button_C.setTextColor(Color.parseColor(prefs.getString("color_prefs", String.valueOf(R.color.green))));

In this case my target was to change the Button's text color (Button_C) when I change the color selection from my Preferences (color_prefs).

Spike answered 17/4, 2014 at 14:12 Comment(0)
M
2

Based on CQM's answer and on ovokerie-ogbeta's answer to another question I've come up with this solution:

if (colorAsString.length() == 4) { // #XXX
    colorAsString = colorAsString.replaceAll("#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])", "#$1$1$2$2$3$3");
}

int color = Color.parseColor(colorAsString);
Marty answered 28/2, 2019 at 13:22 Comment(0)
M
1

Get Shared Preferences Color Code in String then Convert to integer and add layout-background color:

    sharedPreferences = getSharedPreferences(mypref, Context.MODE_PRIVATE);
    String sw=sharedPreferences.getString(name, "");
    relativeLayout.setBackgroundColor(Color.parseColor(sw));
Myosotis answered 3/12, 2019 at 17:39 Comment(0)
C
0

Try this, create drawable in your resource...

<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <solid android:color="@color/white"/>
    <size android:height="20dp"
        android:width="20dp"/>
</shape>

then use...

 Drawable mDrawable = getActivity().getResources().getDrawable(R.drawable.bg_rectangle_multicolor);
mDrawable.setColorFilter(Color.parseColor(color), PorterDuff.Mode.SRC_IN);
mView1.setBackground(mDrawable);

with color... "#FFFFFF"

if the color is transparent use... setAlpha

mView1.setAlpha(x); with x float 0-1 Ej (0.9f)

Good Luck

Contrary answered 27/1, 2017 at 21:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.