A Resources Color Is A Pointer, Not A Real Color
I’ve been stymied twice now when trying to create a ColorDrawable by passing an “int” to its constructor, where that int was a “R.color” value. While many Android developers have already learned this lesson, I’m going to write it up here to help me burn it into my memory and to aid others.
Consider the following code, where we try to instantiate a new ColorDrawable.
ColorDrawable backgroundDrawable= new ColorDrawable(R.color.background_selected);
where the value of R.color.background_selected is defined in color.xml as
#7f00ccff
Both R.color.background_selected and the argument to the ColorDrawable constructor are ints, so what’s the problem? Well, R.color.background_selected is a android.content.res.Resources pointer, not the int represented by #7f00ccff. The solution is to convert the Resources pointer to a real color int, and pass that on the constructor.
int colorBack = resources.getColor(R.color.background_selected); ColorDrawable backgroundDrawable= new ColorDrawable(colorBack);