Android snippet: refer to a colour in code / programmatically

Here’s another possible Android gotcha.  Say you have a colour like this defined in an xml file:

<color name=”red”>#FF0000</color>

Then in some code you do something like:

TextView textView = new TextView(context);

You’ll find that the text comes out like some darkish grey colour and this is because it used the resource id (which is a large int) and not the colour value.  To get this to work as expected you need to make a small change

TextView textView = new TextView(context);

Naturally, you need to get the resources from a context, as shown above.

Leave a Reply

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

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

Google photo

You are commenting using your Google 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