366

I'd like to use a color from an hexa string such as "#FFFF0000" to (say) change the background color of a Layout. Color.HSVToColor looks like a winner but it takes a float[] as a parameter.

Am I any close to the solution at all?

svick
  • 236,525
  • 50
  • 385
  • 514
Johann
  • 12,158
  • 11
  • 62
  • 89
  • Possible duplicate of [Converting android color string in runtime into int](http://stackoverflow.com/questions/3849607/converting-android-color-string-in-runtime-into-int) – Shubham A. Feb 25 '16 at 05:50

14 Answers14

674

Try Color class method:

public static int parseColor (String colorString)

From Android documentation:

Supported formats are: #RRGGBB #AARRGGBB 'red', 'blue', 'green', 'black', 'white', 'gray', 'cyan', 'magenta', 'yellow', 'lightgray', 'darkgray'

AndroidX: String.toColorInt()

Siarhei
  • 2,358
  • 3
  • 27
  • 63
jethro
  • 18,177
  • 7
  • 46
  • 42
  • 5
    Anyone knows how to parse `#000` values ? – Alex Semeniuk Jan 09 '15 at 10:14
  • 9
    Yes, just do: ```if(colorString.length() == 4) { colorString = "#" + StringUtils.repeat(colorString.substring(1, 1), 1) + StringUtils.repeat(colorString.substring(2, 2), 1) + StringUtils.repeat(colorString.substring(3, 3), 1) }```, please correct me if I am wrong – xdevs23 Dec 12 '15 at 11:46
  • 6
    To add to @xdevs23 code, change the if condition to this: `if(colorString.length() == 4 && colorString[0] == '#')` – Zac Jan 11 '16 at 19:40
  • 4
    Your answer would be better if you don't only show the function, but also how to use it: MyView.setBackgroundColor(Color.parseColor("#123456"); – Yvonne Marggraf Jul 24 '18 at 09:20
  • int red = colorString.charAt(1) == '0' ? 0 : 255; int blue = colorString.charAt(2) == '0' ? 0 : 255; int green = colorString.charAt(3) == '0' ? 0 : 255; Color.rgb(red, blue, green); – GTID Jan 23 '19 at 13:29
  • this return negative int – Fereshteh Naji May 22 '19 at 11:55
  • To avoid mistakes, don't forget to annotate any method that returns or takes a color int with the [`@ColorInt`](https://developer.android.com/reference/androidx/annotation/ColorInt.html) support annotation! – Albert Vila Calvo Aug 02 '19 at 11:39
  • String.toColorInt() method uses Color.parseColor(String) method under the hood. – Zaki Shaikh Feb 02 '23 at 11:25
290

Try:

myLayout.setBackgroundColor(Color.parseColor("#636161"));
ndeverge
  • 21,378
  • 4
  • 56
  • 85
invisbo
  • 3,399
  • 1
  • 16
  • 20
61

This question comes up for a number of searches related to hex color so I will add a summary here.

Color from int

Hex colors take the form RRGGBB or AARRGGBB (alpha, red, green, blue). In my experience, when using an int directly, you need to use the full AARRGGBB form. If you only have the RRGGBB form then just prefix it with FF to make the alpha (transparency) fully opaque. Here is how you would set it in code. Using 0x at the beginning means it is hexadecimal and not base 10.

int myColor = 0xFF3F51B5;
myView.setBackgroundColor(myColor);

Color from String

As others have noted, you can use Color.parseColor like so

int myColor = Color.parseColor("#3F51B5");
myView.setBackgroundColor(myColor);

Note that the String must start with a #. Both RRGGBB and AARRGGBB formats are supported.

Color from XML

You should actually be getting your colors from XML whenever possible. This is the recommended option because it makes it much easier to make color changes to your app. If you set a lot of hex colors throughout your code then it is a big pain to try to change them later.

Android material design has color palates with the hex values already configured.

These theme colors are used throughout your app and look like this:

colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <color name="primary">#3F51B5</color>
  <color name="primary_dark">#303F9F</color>
  <color name="primary_light">#C5CAE9</color>
  <color name="accent">#FF4081</color>
  <color name="primary_text">#212121</color>
  <color name="secondary_text">#757575</color>
  <color name="icons">#FFFFFF</color>
  <color name="divider">#BDBDBD</color>
</resources>

If you need additional colors, a good practice to follow is to define your color in two steps in xml. First name the the hex value color and then name a component of your app that should get a certain color. This makes it easy to adjust the colors later. Again, this is in colors.xml.

<color name="orange">#fff3632b</color>
<color name="my_view_background_color">@color/orange</color>

Then when you want to set the color in code, do the following:

int myColor = ContextCompat.getColor(context, R.color.my_view_background_color);    
myView.setBackgroundColor(myColor);

Android Predefined colors

The Color class comes with a number of predefined color constants. You can use it like this.

int myColor = Color.BLUE;
myView.setBackgroundColor(myColor);

Other colors are

  • Color.BLACK
  • Color.BLUE
  • Color.CYAN
  • Color.DKGRAY
  • Color.GRAY
  • Color.GREEN
  • Color.LTGRAY
  • Color.MAGENTA
  • Color.RED
  • Color.TRANSPARENT
  • Color.WHITE
  • Color.YELLOW

Notes

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
24

Convert that string to an int color which can be used in setBackgroundColor and setTextColor

String string = "#FFFF0000";
int color = Integer.parseInt(string.replaceFirst("^#",""), 16);

The 16 means it is hexadecimal and not your regular 0-9. The result should be the same as

int color = 0xFFFF0000;
700 Software
  • 85,281
  • 83
  • 234
  • 341
  • how can i convert String color ="80000000"; to int color=? – Ashish Sahu May 24 '14 at 01:01
  • I think the string version aught to be `#80000000` in which case the int version would be `int color = 0x80000000;`. If that doesn't work then post a [new question](http://stackoverflow.com/questions/ask) with more details so more people than me will notice it. Keep in mind `#80000000` is a translucent black color. – 700 Software May 24 '14 at 13:01
  • I know int would be int color =0x80000000 but my problem is how convert it...But now l'll solved my problem self with int color =parseColor("#"+"80000000");...thanks for reply . – Ashish Sahu May 24 '14 at 13:12
  • I got an exception using your code: java.lang.NumberFormatException: Invalid int: "FFFF0000" – novas1r1 Jun 20 '17 at 11:30
16

It's

int color =  Color.parseColor("colorstring");
Patricia
  • 2,885
  • 2
  • 26
  • 32
15

Try this:

vi.setBackgroundColor(Color.parseColor("#FFFF0000"));
MindBrain
  • 7,398
  • 11
  • 54
  • 74
12

I use this and it works great for me for setting any color I want.

public static final int MY_COLOR = Color.rgb(255, 102, 153);

Set the colors using 0-255 for each red, green and blue then anywhere you want that color used just put MY_COLOR instead of Color.BLUE or Color.RED or any of the other static colors the Color class offers.

Just do a Google search for color chart and it you can find a chart with the correct RGB codes using 0-255.

Opy
  • 2,119
  • 3
  • 18
  • 22
9

Try this

int colorInt = Color.parseColor("#FF00FFF0");
bg.setBackgroundColor(colorInt);

where bg is a view or layout to which you want to set the background color.

M Umer
  • 353
  • 6
  • 13
6

In Xamarin Use this

Control.SetBackgroundColor(global::Android.Graphics.Color.ParseColor("#F5F1F1"));
Shanmugasundharam
  • 2,082
  • 23
  • 32
5

Try using 0xFFF000 instead and pass that into the Color.HSVToColor method.

Dave Long
  • 9,569
  • 14
  • 59
  • 89
  • 2
    I would expect that you should replace that third F with a zero. In the OP, I think the first two F characters are used to set the opacity. – 700 Software Mar 09 '11 at 16:14
4

If you define a color in your XML and want to use it to change background color or something this API is the one your are looking for:

 ((TextView) view).setBackgroundResource(R.drawable.your_color_here);

In my sample I used it for TestView

M.Hefny
  • 2,677
  • 1
  • 26
  • 30
0

For shortened Hex code

int red = colorString.charAt(1) == '0' ? 0 : 255;
int blue = colorString.charAt(2) == '0' ? 0 : 255;
int green = colorString.charAt(3) == '0' ? 0 : 255;
Color.rgb(red, green,blue);
GTID
  • 538
  • 2
  • 6
  • 19
0

There is no pre-defined class to implement directly from hex code to color name so what you have to do is Try key value pair concept simple, follow this code.

String hexCode = "Any Hex code" //#0000FF

HashMap<String, String> color_namme = new HashMap<String, String>();
                        color_namme.put("#000000", "Black");
                        color_namme.put("#000080", "Navy Blue");
                        color_namme.put("#0000C8", "Dark Blue");
                        color_namme.put("0000FF", "Blue");
                        color_namme.put("000741", "Stratos");
                        color_namme.put("001B1C", "Swamp");
                        color_namme.put("002387", "Resolution Blue");
                        color_namme.put("002900", "Deep Fir");
                        color_namme.put("002E20", "Burnham");
                        for (Map.Entry<String, String> entry : color_namme.entrySet()) {
                            String key = (String) entry.getKey();
                            String thing = (String) entry.getValue();
                            if (hexCode.equals(key))
                                Color_namme.setText(thing); //Here i display using textview


                        }
0

I Have created a Complete Answer :

    /**
     * Input: Hex Value of ARGB, eg: "#FFFF00FF", "#FF00FF", "#F0F"
     * Output:  Float Color Array with  with red, green,
     * blue and alpha (opacity) values,
     * eg:  floatArrayOf(0.63671875f, 0.76953125f, 0.22265625f, 1.0f)
     */
    private fun getFloatArrayFromARGB(argb: String): FloatArray {
        val colorBase: Int = if (argb.length == 4) {
            val red = if (argb[1] == '0') 0 else 255
            val green = if (argb[2] == '0') 0 else 255
            val blue = if (argb[3] == '0') 0 else 255
            Color.rgb(red, green, blue)
        } else {
            Color.parseColor(argb)
        }
        val red = Color.red(colorBase)
        val green = Color.green(colorBase)
        val blue = Color.blue(colorBase)
        val alpha = Color.alpha(colorBase)
        return floatArrayOf(
            red / 255f,
            green / 255f,
            blue / 255f,
            alpha / 255f
        )
    }

Usage:

   private val colorValue = getFloatArrayFromARGB("#F0F")

Hope it help somebody

Hitesh Sahu
  • 41,955
  • 17
  • 205
  • 154