PPartisan
PPartisan

Reputation: 8231

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.

Upvotes: 1

Views: 977

Answers (3)

Harish Sridharan
Harish Sridharan

Reputation: 1090

No. Its totally up to you where you define the colors. The advantage of keeping them in xml is you can use those colors in your xml layouts/themes as well.

Eg:

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/color_red_500" />

If you're fed up passing Context to extract colors, I would suggest you to have a static singleton instance for your Application class

Eg:

public class MyApplication extends Application {
    private static MyApplication instance;

    public static MyApplication getInstance() {
        return instance;
    }

    public void onCreate() {
        super.onCreate();
        instance = this;
    }
}

Then use it like MyApplication.getInstance().getResources().getColor(R.color.red_500);

Upvotes: 1

RobVoisey
RobVoisey

Reputation: 1083

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.

Upvotes: 0

Jordi Castilla
Jordi Castilla

Reputation: 26961

Actually there is not a defined convention for this.


Which matters most in this cases is

  • clarity
  • performance
  • scalability

If, in your case, this remove declaration duplicates and makes your code clearer, not affecting performance, yes, you can and MUST use it.

But note: this is not a general rule, you must analize each case individually and decide wisely, for other cases, use AppColors class may create duplicities or performance problems (if many requests) instead of using database table.

Upvotes: 1

Related Questions