371

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?

1

16 Answers 16

682

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

Sign up to request clarification or add additional context in comments.

8 Comments

Anyone knows how to parse #000 values ?
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
To add to @xdevs23 code, change the if condition to this: if(colorString.length() == 4 && colorString[0] == '#')
Your answer would be better if you don't only show the function, but also how to use it: MyView.setBackgroundColor(Color.parseColor("#123456");
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);
|
294

Try:

myLayout.setBackgroundColor(Color.parseColor("#636161")); 

For Compose:

Box(modifier = Modifier.background(Color(0xFF636161))) 

1 Comment

if you are using xamarin.. the code is this Android.Graphics.Color.ParseColor("#636161") with "P" to Upper
65

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

Comments

25

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; 

4 Comments

how can i convert String color ="80000000"; to int color=?
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.
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 .
I got an exception using your code: java.lang.NumberFormatException: Invalid int: "FFFF0000"
16

It's

int color = Color.parseColor("colorstring"); 

Comments

15

Try this:

vi.setBackgroundColor(Color.parseColor("#FFFF0000")); 

Comments

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.

Comments

11

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.

Comments

6

In Xamarin Use this

Control.SetBackgroundColor(global::Android.Graphics.Color.ParseColor("#F5F1F1")); 

Comments

5

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

1 Comment

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.
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

Comments

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

Comments

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

Comments

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 }

Comments

0

For kotlin extension function

fun String.toColor(): Int? { return if (this.isNotEmpty()) { Color.parseColor(this) } else { null } 

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.