How to Set a Color In Android

Changing Colors in Android and Naming Them for Convenience

An Android color is a 32-bit integer value consisting of four eight bit parts, ARGB. The four parts are the amount of red, green and blue that is in the color, plus how opaque (see through) is the color, which is called the alpha value, the lower the alpha value the more transparent the color appears. (Note that in the United Kingdom color is spelt colour.)

The alpha value is the highest (first) byte in the 32-bit value followed by the red, then green and finally the blue byte. Hence it is referred to as an ARGB value with each letter representing the type and order of the byte. This format allows for easy representation as a hexadecimal number in Java:

The three byes representing the color values provide over 16 million color possibilities in Android (256 x 256 x 256 = 16,777,216). A color depth better than the human eye (stated in the Wikipedia article). Plus all these colors can range from transparent, 0, to opaque, 255.

Named Color Resources in Android

To help with handling colors in Android they can be made into a resource for easy of reuse. Either open an existing resource file or create a new one. For example in Eclipse with a Android project open select the res/values folder. Then use the File menu (or the context menu on the values folder) to add an Android XML File. Give the file a name, e.g. colors.xml and add a color element:

Use getColor() to read the color value from the resource.

If the color is solid (full alpha value) then the color resource can leave the alpha value out. Though for clarity and future maintenance it is wise to be explicit and always define all four parts of an Android color: Continue reading