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?

1
  • 1
    see in import area you have import android.R; remove that one it will work Jul 13, 2013 at 10:25

5 Answers 5

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

4
  • 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, 2016 at 9: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, 2016 at 9: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, 2016 at 20:08
  • An int is an int. How would you distinguish between an int resource and an int color?
    – Blackbelt
    Sep 22, 2016 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)

2

UPDATE 6 july 2016

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

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

1

Why dont try to pars color in fowling way

int colorCode = Color.parseColor("#ffffff") ;
setColor(colorCode) ;
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

1
  • Doesn't work for me. There doesn't seem to be a Color initializer with int.
    – Manuel
    Apr 28, 2019 at 13:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.