How to get a Color from hexadecimal Color String

AndroidColorsHex

Android Problem Overview


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?

Android Solutions


Solution 1 - Android

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

Solution 2 - Android

Try:

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

Solution 3 - Android

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

Solution 4 - Android

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;

Solution 5 - Android

It's

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

Solution 6 - Android

Try this:

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

Solution 7 - Android

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.

Solution 8 - Android

XML file saved at res/values/colors.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <color name="opaque_red">#f00</color>
   <color name="translucent_red">#80ff0000</color>
</resources>

This application code retrieves the color resource:

Resources res = getResources();
int color = res.getColor(R.color.opaque_red);

This layout XML applies the color to an attribute:

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textColor="@color/translucent_red"
    android:text="Hello"/>

Solution 9 - Android

In Xamarin Use this

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

Solution 10 - Android

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

Solution 11 - Android

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

Solution 12 - Android

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.

Solution 13 - Android

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

Solution 14 - Android

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


                        }

Solution 15 - Android

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohannView Question on Stackoverflow
Solution 1 - AndroidjethroView Answer on Stackoverflow
Solution 2 - AndroidinvisboView Answer on Stackoverflow
Solution 3 - AndroidSuragchView Answer on Stackoverflow
Solution 4 - Android700 SoftwareView Answer on Stackoverflow
Solution 5 - AndroidPatricia HeimfarthView Answer on Stackoverflow
Solution 6 - AndroidMindBrainView Answer on Stackoverflow
Solution 7 - AndroidOpyView Answer on Stackoverflow
Solution 8 - AndroidAZ_View Answer on Stackoverflow
Solution 9 - AndroidShanmugasundharamView Answer on Stackoverflow
Solution 10 - AndroidDave LongView Answer on Stackoverflow
Solution 11 - AndroidM.HefnyView Answer on Stackoverflow
Solution 12 - AndroidM UmerView Answer on Stackoverflow
Solution 13 - AndroidGTIDView Answer on Stackoverflow
Solution 14 - AndroidPArikshit KAmatView Answer on Stackoverflow
Solution 15 - AndroidHitesh SahuView Answer on Stackoverflow