user2005938
user2005938

Reputation: 179

Calling a color from xml file

If i have an xml file with custom colors like this in res/values/colors:

<?xml version="1.0" encoding="utf-8"?> 
<resources>
 <drawable name="red">#ff0000</drawable>
 <drawable name="blue">#0000ff</drawable>
 <drawable name="green">#00ff00</drawable>
</resources>

How can I use colors or other values from it in other code?

How can I use these for arguments? Something like:

    int green = context.getResources().getColor(R.color.green);
    g.drawRect(1, 1, 181, 121, green);

gives errors in logcat and crashes the program. So if colors.xml is in res/values/ and I have context imported how can I use green, for example in an argument?

Upvotes: 3

Views: 2511

Answers (1)

anthropomo
anthropomo

Reputation: 4120

First, change drawable to color in your xml.

Then you need to have context. It goes like this:

context.getResources().getColor(R.color.green);

It returns an int color value.

Edit:

For other values, see the functions here:

http://developer.android.com/reference/android/content/res/Resources.html

I like tp get all my xml colors once and pass them around from there so I am not typing the above over and over. Not sure if this is considered best practice.

If you want to use this in a Paint, it could be:

// Declare this at the beginning:
Paint green paint;
// This goes in the constructor:
greenPaint = new Paint();
greenPaint.setColor(context.getResources().getColor(R.color.green));
// then draw something in onDraw, for example:
canvas.drawRect(5,5,5,5, greenPaint);

If you want to use it in multiple Paints, etc. save it as an int:

int greenNum = context.getResources().getColor(R.color.green);

Upvotes: 2

Related Questions