2

I am working on an Android app, which uses some html data from a website. I have a few pieces of text that are using html colors. Like 'red' or 'green'. Is there any way to convert those strings to HEX values in Java?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Black Magic
  • 2,706
  • 5
  • 35
  • 58

4 Answers4

3

String hexvalue = Integer.toHexString(Color.parseColor("red"));

//hexvalue is now "ffffff00"

Orphamiel
  • 874
  • 13
  • 22
  • [Documentation](http://developer.android.com/reference/android/graphics/Color.html) Also, this doesn't seem to go to HEX, unless I'm confused. – Zach Lysobey Dec 31 '13 at 16:10
  • [Instructions on doing the int -> hex` conversion](http://stackoverflow.com/questions/6539879/how-to-convert-a-color-integer-to-a-hex-string-in-android) – Zach Lysobey Dec 31 '13 at 16:11
2

This will return a color int

int intColor = android.graphics.Color.parseColor("red") //  -65536

Then you can convert to HEX like so:

String hexColor = String.format("#%06X", (0xFFFFFF & intColor));
Community
  • 1
  • 1
Zach Lysobey
  • 14,959
  • 20
  • 95
  • 149
0

You could easily add the list of HTML colors within your app and translate them. 140 color names are defined in the HTML and CSS color specification. The list is here.

Given that, it would be trivial to have a HashMap that translates the color names into the appropriate Hex code.

You could also use Color.parseColor as defined here. That would yield an android color-int, which can be converted to hex like this:

String hexColor = String.format("#%06X", (0xFFFFFF & intColor));
David S.
  • 6,567
  • 1
  • 25
  • 45
0

If they're using standard CSS 'red' and 'green' then it's equivilent to #FF0000 (rgb(255,0,0)) and #00FF00 (rgb(0,255,0)) respectively.

You can also look-up any hex value for a named color in the CSS standard easily at http://www.w3schools.com/cssref/css_colornames.asp