Adam
Adam

Reputation: 2202

How to get foreground color from hexadecimal color?

I need to know how to get code for foreground color if I know hexadecimal color for that color.

<string name="name">Asavbasb <font fgcolor="#33b5e5">look</font></string>

This is code for my color in hexadecimal #33b5e5, but if I use it in fgcolor="33b5e5", selected text is white and not blue, so my question is how can I get code for that foreground color?

Upvotes: 0

Views: 1535

Answers (4)

Edward Falk
Edward Falk

Reputation: 10083

Prior to 4.x, you could do this:

<string name="error"><font fgcolor="#ff33b5e5">Error!</font></string>

However, bug https://code.google.com/p/android/issues/detail?id=58192 broke this functionality because it introduced an integer parser that can't handle numbers with the highest bit set, and unfortunately you can't omit the opacity part of the color (which most people would prefer to set to ff as in this example.)

I just yesterday learned a clever work-around. What you do is negate the hex color value in two's complement. How you do this depends on your hex calculator, but the easiest way is to subtract your color from 0x100000000. In your case, that would result in 0x100000000 - 0xff33b5e5 = 0xcc4a1b. (Or you could just invert it, e.g. 00cc4a1a which would be close enough). You then negate this again with a minus sign:

<string name="error"><font fgcolor="-#cc4a1b">Error!</font></string>

and voilla! you have your desired color.

Kudos to TWiStErRob for figuring this out in https://stackoverflow.com/a/11577658/338479

ETA: I just discovered that this will crash your app if you do it on a 2.x system; it throws a NumberFormat exception

Upvotes: 0

user3139845
user3139845

Reputation:

Have you tried changing your color to fgcolor="#ff33b5e5"?

I think with Android in-line color you need to declare the alpha channel.

Upvotes: 1

gunar
gunar

Reputation: 14710

Instead of above, why don't you use the fromHTML feature?

Something like:

myTextView.setText(Html.fromHtml("Asavbasb <font fgcolor='#33b5e5'>look</font>"));

Or if you really need the color code, you can get it with Color.parseColor(String);

Upvotes: 1

Esteam
Esteam

Reputation: 1941

this is how you can do to create color from hex string and affect it to a TextView:

final int color = Color.parseColor("#33b5e5");
final TextView text = (TextView) findViewById(R.id.text);
text.setTextColor(color);

Upvotes: 0

Related Questions