I want to store the colors I use in the colors.xml file. In addition to using them in an xml-layout, I also want to use these colors in my Java code, when drawing things to the Canvas.
The thing is, I am not always using the colors in a class that extends Application. For example, I have classes for objects that get drawn to the Canvas.
The thing is, I don't want to store the context in each class that needs access to my resources file.
My current solution is the following:
colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorOne">#123456</color>
</resources>
A static class called Attributes for constants, including colors:
public class Attributes {
private static final Resources RESOURCES = MainActivity.getContext().getResources();
public static final int ONE_COLOR = RESOURCES.getColor(R.color.colorOne);
public static final int SOME_OTHER_CONSTANT = 1;
}
MainActivity:
public class MainActivity extends Activity {
private static Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.context = getApplicationContext();
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
}
public static Context getContext() {
return context;
}
}
And, finally in my object class:
public class ScreenArea {
private Rect area;
private Paint paint;
public ScreenArea(Rect area) {
this.area = area;
paint = new Paint();
paint.setColor(Attributes.COLOR_ONE);
}
public void draw(Canvas canvas) {
canvas.drawRect(area, paint);
}
}
Okay, so first of all, this works. But, I am wondering if this is the right way to go. I have been reading about the Singleton class, but most examples are very basic an not focusing on storing constants, like I am doing right now.
So my questions:
- Is this the right way to go or should I implement a Singleton?
- If so, who can point me in the right direction?