How to get a Color from hexadecimal Color String
Asked Answered
B

16

367

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?

Bolduc answered 9/3, 2011 at 16:10 Comment(1)
Possible duplicate of Converting android color string in runtime into intLoaded
A
679

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

Addiction answered 9/3, 2011 at 16:12 Comment(8)
Anyone knows how to parse #000 values ?Cressi
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 wrongCuff
To add to @Cuff code, change the if condition to this: if(colorString.length() == 4 && colorString[0] == '#')Moule
Your answer would be better if you don't only show the function, but also how to use it: MyView.setBackgroundColor(Color.parseColor("#123456");Bizerte
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);Deepset
this return negative intTosha
To avoid mistakes, don't forget to annotate any method that returns or takes a color int with the @ColorInt support annotation!Memoir
String.toColorInt() method uses Color.parseColor(String) method under the hood.Archfiend
K
293

Try:

myLayout.setBackgroundColor(Color.parseColor("#636161"));
Kilk answered 1/6, 2012 at 9:38 Comment(1)
if you are using xamarin.. the code is this Android.Graphics.Color.ParseColor("#636161") with "P" to UpperCicala
A
63

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

Aulic answered 8/2, 2017 at 2:25 Comment(0)
B
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;
Barbuto answered 9/3, 2011 at 16:12 Comment(4)
how can i convert String color ="80000000"; to int color=?Lakeshialakey
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 with more details so more people than me will notice it. Keep in mind #80000000 is a translucent black color.Barbuto
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 .Lakeshialakey
I got an exception using your code: java.lang.NumberFormatException: Invalid int: "FFFF0000"Sketchbook
A
16

It's

int color =  Color.parseColor("colorstring");
Arizona answered 26/9, 2015 at 10:38 Comment(0)
S
15

Try this:

vi.setBackgroundColor(Color.parseColor("#FFFF0000"));
Squander answered 7/9, 2015 at 13:35 Comment(0)
B
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.

Brinkmanship answered 2/11, 2011 at 13:40 Comment(0)
G
10

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.

Gerdi answered 13/10, 2021 at 4:48 Comment(0)
A
6

In Xamarin Use this

Control.SetBackgroundColor(global::Android.Graphics.Color.ParseColor("#F5F1F1"));
Anaphase answered 21/9, 2017 at 10:59 Comment(0)
M
5

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

Messer answered 9/3, 2011 at 16:13 Comment(1)
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.Barbuto
I
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

Ilana answered 27/11, 2014 at 21:25 Comment(0)
I
1

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

Initiatory answered 31/7, 2021 at 10:16 Comment(0)
D
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);
Deepset answered 23/1, 2019 at 13:30 Comment(0)
G
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


                        }
Gladi answered 13/2, 2021 at 19:25 Comment(0)
R
0

For kotlin extension function

fun String.toColor(): Int? {
    return if (this.isNotEmpty()) {
        Color.parseColor(this)
    } else {
        null
    }
Rossiya answered 22/10, 2023 at 14:42 Comment(0)
C
0

Here is a delicate Kotlin extension function for a Jetpack Compose Color

import androidx.compose.ui.graphics.Color

typealias AndroidColor = android.graphics.Color

fun Color.Companion.fromHex(hexColorCode: String): Color {
    val processedColor = hexColorCode.uppercase().removePrefix("#")

    val colorInt = when (processedColor.length) {

        3 -> { // Short RGB format (#RGB)
            val (r, g, b) = processedColor.map { it.toString().repeat(2) }
            AndroidColor.parseColor("#$r$g$b")
        }

        4 -> { // Short ARGB format (#ARGB)
            val (a, r, g, b) = processedColor.map { it.toString().repeat(2) }
            AndroidColor.parseColor("#$a$r$g$b")
        }

        // Standard RGB or ARGB formats
        6, 8 -> AndroidColor.parseColor("#$processedColor")

        else -> {
            Color.Black.hashCode() // Default color if the input is not hex
        }
    }

    return Color(colorInt)
}

Usage:

val color = Color.fromHex("#80FF5733")
Compatriot answered 20/12, 2023 at 9:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.