How To Define Custom Color Variables In Android Studio class provide some color constants which can be used directly in android application. For example, BLACK, WHITE, RED, GREEN, BLUE, YELLOW, CYAN, MAGENTA, GRAY, LTGRAY (light gray), DKGRAY (dark gray). But you may find that it is not enough, sometimes you need more colors. So this article will show you how to define custom color variables in android studio.

1. Custom Color Variable Advantages.

Define and use color variable instead of color value such as “#112233” in java code or xml file has below advantages.

  1. More easy to remember : You can assign a more meaningful name to a color value. Such as backgroundColorRed, from this variable name we can see that this variable is not only represent red color, but also represent a background color.
  2. More easy to maintain : Suppose you use one color value in a lot of places such as java source code, xml files etc. If you want to change the color vaue, you should change so many files. If you use a defined color variable, you just need to change color definition file in one place.

2. How To Define A Custom Color Variable.

  1. Go to android studio Project View —> Android Sub view. Right click app / res / values folder. Click New —> Values resource file menu.
    create new colors xml file in android studio
  2. Input colors in File name input box, click OK button.colors xml file detail information dialog
  3. Then colors.xml file will be created in left panel under app / res / values folder. Double click it, input below color definition xml data in it. The name attribute value will be used as variable name referred in other xml file or java source code. #f1a86c is just the color RGB value that variable represent.
    <color name="colorRed">#ff0000</color>
    <color name="colorOrange">#f1a86c</color>

    colors xml file content

  4. For each color variable, there is a color block at the line beginning. Click it, there will popup Choose Color dialog which can make modify color more easily.

3. How To Use Custom Color Variable Defined In Colors.xml.

The custom color variable can be used in both xml or java file. It is easy to refer them.

  1. Use custom color variable in xml file such as layout xml file example. @color/colorVariableName @color/colorOrange.
        android:background="@color/colorRed" />
        android:background="@color/colorOrange" />
  2. Use custom color variable in java file example. R.color.colorVariableName R.color.colorRed. R is the android auto created resource class.
    final int[] colorArr = new int[];
        R.color.colorRed, R.color.colorOrange
0 0 votes
Article Rating
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x