32

I have a custom View that uses Paint and Canvas to draw objects. My question is how to set:

int color = R.color.white;
paint.setColor(color);

from my /res/valuse/color.xml which includes resources like

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="white">#FFFFFF</color>
    <color name="black">#000000</color>
    ...
</resources>
Jacob R
  • 1,243
  • 1
  • 16
  • 23
Vasil Valchev
  • 5,701
  • 2
  • 34
  • 39

5 Answers5

65
int color = ContextCompat.getColor(context, R.color.white);
paint.setColor(color);

The setColor() method takes a color number as int value, but not a resource id which is an int as well.

Johnny Five
  • 987
  • 1
  • 14
  • 29
olshevski
  • 4,971
  • 2
  • 35
  • 34
14

first get your color from xml file

int color = context.getResources().getColor(R.color.colorPrimary); // old

is deprecated now, use this instead

int color = ContextCompat.getColor(context, R.color.colorPrimary); // new

set color

paint.setColor(color);

xml file preview: res/values/color.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
</resources>
Vasil Valchev
  • 5,701
  • 2
  • 34
  • 39
11

Try using color.white:

paint.setColor(Color.white)
splash
  • 13,037
  • 1
  • 44
  • 67
Hani Hussein
  • 159
  • 4
  • 2
    hmm ... looks like this doesn't answer the question (at least not how I understand it :-) - which is about how to access a custom color declared in the resources (vs. a pre-defined color) – kleopatra Nov 23 '12 at 09:39
  • This does not answer the question, which is to get the int value of a color predefinied from *resources* for use with paint.setColor(...). And it should be Color.WHITE (all caps), not Color.white. Completely useless. – ONE Jun 24 '19 at 02:48
2
paint.setColor(Color.parseColor("#FFFFFF"))
0

Set any color

paint.setColor( Color.rgb(R, G, B) )
Dharman
  • 30,962
  • 25
  • 85
  • 135
Oras
  • 120
  • 1
  • 9