colors.xml resource does not work

b10hazard picture b10hazard · Jul 10, 2011 · Viewed 7.8k times · Source

I created a colors.xml file in my Android app under /res/values/colors.xml. The contents are...

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="Green">#00ff00</color>
</resources>

I try to update the background of my a TableRow using...

    TableRow test = (TableRow)findViewById(R.id.tableRow2);
    test.setBackgroundColor(R.color.Green);

This does not set it as green, it is gray instead. No matter what values I add to the colors.xml file, it is always the same gray color. However this does work...

    TableRow test = (TableRow)findViewById(R.id.tableRow2);
    test.setBackgroundColor(android.graphics.Color.GREEN);

Is something wrong with my colors.xml?

Answer

inazaruk picture inazaruk · Jul 10, 2011

You should use this instead:

TableRow test = (TableRow)findViewById(R.id.tableRow2);
test.setBackgroundColor(getResources().getColor(R.color.Green));

Its unfortunate that resource ID and color have same type: int. You should get color value from resources via getColor() and use that valu as color. While you are using resource ID as color.