Groot
Groot

Reputation: 493

Android Convert Int to Hex Color

How can I convert an int to a hex color and use it with a ColorDrawable?

I have tried other methods that use a string, and I get "ColorDrawable cannot be applied to java.lang.String".

I have tried:

String strColor = String.format("#%06X", 0xFFFFFF & actionColor);

actionBar.setBackgroundDrawable(new ColorDrawable(strColor));

But I cannot apply that to a ColorDrawable. I am trying to set the color of the ActionBar with hex.

Thanks

Upvotes: 1

Views: 3162

Answers (3)

Bismarck
Bismarck

Reputation: 96

Maybe I am not fully understanding the question, but if I'm getting it correctly, depending on your application purposes perhaps you could just use the int directly as follows:

   actionBar.setBackgroundColor(actionColor);

Assuming actionColor has the color you need, the function will take the int in its "hex form" and know what to do.

Upvotes: 0

Typo
Typo

Reputation: 1900

You can think about a color as composed of 3 components. RGB. In your example you have 0xffffff. The first ff is the red component, the second ff is green component the third FF is the blue component. Change those hexadecimal values you can get your colors.

e.g. use

int color = Color.rgb(255, 255, 175);

Upvotes: 1

Olayinka
Olayinka

Reputation: 2845

The ColorDrawable takes an int as parameter not string. I suppose actionColor is also an integer (color hex) so you should do this.

int color = 0xFFFFFF & actionColor;
actionBar.setBackgroundDrawable(new ColorDrawable(color));

Upvotes: 2

Related Questions