How To Define Custom Color Variables In Android Studio

The android class provides some color constants which can be used directly in an 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 the color variable instead of color value such as “#112233” in java code or XML file has below advantages.

  1. Easier 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 represented the red color but also represent a background color.
  2. Easier 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 value, you should change so many files. If you use a defined color variable, you just need to change the color definition file in one place.

2. How To Define A Custom Color Variable.

  1. Go to android studio Project View —> Android Subview.
  2. Right-click app/res/values folder. Click New —> Values resource file menu item to popup the New Resource File dialog window.
  3. In the New Resource File dialog window, input keyword colors in the File name input box, select main in the Source set drop-down list,  input values in the Directory name input text box, then click the OK button.
  4. Then colors.xml file will be created in the left panel under the app/res/values folder. Double click it, input below color definition XML data in it. The name attribute value ( for example “colorRed” ) will be used as a variable name referred to in other XML files or java source codes. #f1a86c is just the color RGB value that the color variable represents.
    <?xml version="1.0" encoding="utf-8"?>
       <color name="colorRed">#ff0000</color>
       <color name="colorOrange">#f1a86c</color>
  5. For each color variable, there is a color block at the line beginning. Click it, there will popup Choose Color dialog which can let you modify color more easily.

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

The custom color variations can be used in both XML and java files. It is easy to refer them.

  1. Use the custom color variable in an XML file such as the layout XML file example. @color/colorVariableName @color/colorOrange.
        android:background="@color/colorRed" />
        android:background="@color/colorOrange" />
  2. Use the custom color variable in the 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

4. How To Define A Color Variable And Use It Programmatically.

4.1 Question1.

  1. I want to define a color variable globally in my android project.
  2. Then I can use it to change some of the UI component’s background colors.
  3. Below is the source code.
    # define a global variable that save the colors.
    Color globalColor = new Color();
    # set the button background color use the above global color variable.
  4. But this does not work, how can I do it like that?

4.2 Answer1.

  1. The Button object’s setBackgroundColor() method only accept integer type parameter, but you pass a Color object to the method, this is not correct.
  2. You can create a color resource file in your android project, and give the color resource an id like back_ground_color.
  3. Then you can use the code getResources().getColor(R.color.back_ground_color) to get the customized color.
  4. And then set the color to the button’s background color like below.
    int global_back_color = getResources().getColor(R.color.back_ground_color)
  5. If you want to change the color value globally later, you can just change it in the android project color resource file.

5. How To Change Color Value Got From Color Resource File In Source Code Dynamically.

5.1 Question1.

  1. I define a color variable color_1 in my android project’s app/res/values/colors.xml file like below.
    <?xml version="1.0" encoding="utf-8"?>
          <color name="color_1">#ff0000</color>
  2. I want to use this color in activity1, so I get it with the code getResources().getColor(R.color.color_1).
  3. But I want to change it to another color in activity2, can I just do it with the code R.color.color_1 = Color.BLUE?
  4. If I change it in activity2‘s local method not globally, will the change exist when I call the code R.color.color_1 in activity3?
  5. What I want is the code R.color.color_1 returns Color.BLUE in activity2 and acrivity3, and the code return #ff0000 in activity1. How can I do that?

5.2 Answer1.

  1. You can define a special color resource in the app/res/values/colors.xml file like below. There are 2 color resources in the below resource file, the the_special_color_id is just a placeholder for the color resource, you can change it’s color as you need in the source code later.
    <?xml version="1.0" encoding="utf-8"?> 
        <color name="color_1">#ff0000</color> 
        <color name="the_special_color_id">#ff0000</color> 
  2. Then you can create a customized resource class MyResource that extends the android Resources class, and override it’s getColor() method as below.
  3. The getColor() method will return different colors by the passed in color resource id. If you pass in the_special_color_id it will return Color.BLUE, you can see the code comments for a detailed explanation.
    // Define a customized Resource class that extends the Android Resources
    public class MyResource extends Resources {
        // This is the MyResource class constructure method.
        public MyResource(Resources original) {
            super(original.getAssets(), original.getDisplayMetrics(), original.getConfiguration());
        // Override the getColor(int id) method.
        @Override public int getColor(int id) throws NotFoundException {
            return getColor(id, null);
        // The above getColor(int id) mehtod will call this getColor(int id, Theme theme) method.
        @Override public int getColor(int id, Theme theme) throws NotFoundException {
            // Get the resource entry name with the provided color resource id. 
            String resourceEntryName = getResourceEntryName(id);
            // Return different color by the passed in color resource entry name.
            switch (resourceEntryName) {
                case "the_special_color_id":
                    // return Color.BLUE, you can also return the color value got from SharedPreferences or other API invoke returned value. 
                    return Color.BLUE;
                    // return the color by invoke the super.getColor() method.
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        return super.getColor(id, theme);
                    return super.getColor(id);
  4. Then you can create an instance of the above MyResource class in your android activity class, and use it’s getColor() method to return different colors with different color resource id.
  5. Below is an example source code of the android activity class.
    // The activity that use the customize resource object to get color resource.
    public class Activity1 extends AppCompatActivity {
        // Define a variable of MyResource type.
        private MyResource myres = null;
        @Override public Resources getResources() {
            if (myres == null) {
                # return an MyResource object.
                myres = new MyResource(super.getResources());
            return myres;
        // Then you can call the local variable myres.getColor() method to get different colors by pass in different color id.
        // Set TextView background color to
        TextView tvTitle = (TextView)findViewById(;
        // Set Button background color to
        Button btn1 = new Button(this);

Leave a Comment

Your email address will not be published. Required fields are marked *

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