Reputation: 8231
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
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
Reputation: 1083
Best to check the case that suits your needs but here are some arguments against.
To read more on the subject, try reading this: http://developer.android.com/guide/topics/resources/overview.html.
Upvotes: 0
Reputation: 26961
Actually there is not a defined convention for this.
Which matters most in this cases is
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