Home > Development > A Resources Color Is A Pointer, Not A Real Color

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);
About these ads
Categories: Development Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: