17

Android has 2 types of colors: R.color and color Layout uses R.color (I need holo_blue_light: 17170450 (0x01060012))

but functions (such as setColor()) have the other type of input int (i.e. CYAN: -16711681 (0xff00ffff)).

Negation of R.color returns incorrect colors. What should I do to convert them?

Sieva Kimajeŭ
  • 337
  • 1
  • 3
  • 12

5 Answers5

23

Since getResources().getColor is now deprecated, you can use:

ContextCompat.getColor(getResources(), R.color.idOfColour)

old answer

Use

 getResources().getColor(R.color.idOfColour);

it returns the int color you are looking for. If the colour comes with Android you can get its id with android.R.color.colourId

Blackbelt
  • 156,034
  • 29
  • 297
  • 305
  • deprecated, and the whole api of converting from R.color to color code #xxxxxx, is cumbersome to the extent that it seems much better to just hardcode the color code. Why is it so complex? – carl Sep 22 '16 at 09:28
  • @carl thanks for pointing it out. It is not complex. The reason beyond the deprecation is that the color can be styled with the Context't theme. – Blackbelt Sep 22 '16 at 09:31
  • Well, not complex when you know it, but prior to that. There are many threads around on this function that should be super easy, but are instead another three in the garden of Android timethiefs. Sorry for the harsh verdict :-) I suggest the obvious solution should be an agregated level that can accept R.color as input parameter. Would have saved us time. – carl Sep 22 '16 at 20:08
  • An int is an int. How would you distinguish between an int resource and an int color? – Blackbelt Sep 22 '16 at 20:12
3
  1. Color from resources you get through

    getResources().getColor(R.color.color_id);

  2. Color that you had saved from a view (say background color or text color), which will look like your second example, you may get through

Color.parseColor(String color)

Joel Bodega
  • 644
  • 5
  • 8
2

UPDATE 6 july 2016

ContextCompat.getColor(context, R.color.your_color);

see https://stackoverflow.com/a/31590927/3244382

Community
  • 1
  • 1
PatriceG
  • 3,851
  • 5
  • 28
  • 43
1

Why dont try to pars color in fowling way

int colorCode = Color.parseColor("#ffffff") ;
setColor(colorCode) ;
dharmendra
  • 7,835
  • 5
  • 38
  • 71
1

one more thing I would like to add

int color_int = ContextCompat.getColor(context, R.color.your_color);
Color colorName = new Color(color_int );

you can use colorName as you want

Mina Fawzy
  • 20,852
  • 17
  • 133
  • 156