Search code examples
javaandroidandroid-xmlandroid-color

Defining colour constants in a Java file, not xml


Are there any pitfalls to defining colours as int constants, and accessing them statically, over pulling them from xml every time they are required?

For example, say I define a class called AppColors:

public final class AppColors {

    private AppColors() { throw new AssertionError(); }

    public static final int COLOR_RED_500 = 0xFFF44336;

}

And access the colour with AppColors.COLOR_RED_500, whereas the usual route is getResources().getColor(R.color.red_500).

Aside from the fact that the colour would probably need to be defined twice, once in xml for layout/themes and again in code, defining colours in this way would have the advantage of not requiring repeated getResources() calls and the need to pass Context arguments to methods and constructors of classes that do not inherit from the Context class.


Solution

  • Best to check the case that suits your needs but here are some arguments against.

    1. You listed the major argument in your question, about defining it twice.
    2. You can override the colour in different values files if you so desired, for example a different colour for a different language, screen orientation etc.
    3. You can use the colour in the layout xmls.

    To read more on the subject, try reading this: http://developer.android.com/guide/topics/resources/overview.html.