MikeR
MikeR

Reputation: 93

how to access colors.xml without specifying color name or resource ID (R.color.name)

An XML file containing color names and hex codes is readily available to android programmers, such as:

<?xml version="1.0" encoding="utf-8"?>
<resources>
 <color name="White">#FFFFFF</color>
 <color name="Ivory">#FFFFF0</color>
 ...
 <color name="DarkBlue">#00008B</color>
 <color name="Navy">#000080</color>
 <color name="Black">#000000</color>
</resources>

I can access a specific color using syntax such as:

TextView area1 = (TextView) findViewById(R.id.area);
area1.setBackgroundColor(Color.parseColor(getString(R.color.Navy)));

or

 area1.setBackgroundColor(Color.parseColor("Navy"));

or

Resources res = getResources();  
int rcol = res.getColor(R.color.Navy);  
area1.setBackgroundColor(rcol);  

How can I read in the entire xml file of colors into a String[] of color names AND an int[] of color resources (e.g., R.color.Navy), without having to specify each color name or resource ID?

Upvotes: 6

Views: 5504

Answers (3)

Bal&#225;zs &#201;des
Bal&#225;zs &#201;des

Reputation: 13807

Using the reflection API it's fairly simple (i had a similar problem with drawable-ids not a long time ago), but a lots of more experienced users said, that "Reflection on dalvik is really slow" so BE WARNED!

//Get all the declared fields (data-members):
Field [] fields = R.color.class.getDeclaredFields();

//Create arrays for color names and values
String [] names = new String[fields.length];
int [] colors = new int [fields.length];

//iterate on the fields array, and get the needed values: 
try {
    for(int i=0; i<fields.length; i++) {
        names [i] = fields[i].getName();
        colors [i] = fields[i].getInt(null);
    }
} catch (Exception ex) { 
    /* handle exception if you want to */ 
}

Then if you have those arrays, then you can create a Map from them for easier access:

Map<String, Integer> colors = new HashMap<String, Integer>();

for(int i=0; i<hexColors.length; i++) {
    colors.put(colorNames[i], hexColors[i]);
}

Upvotes: 6

Snicolas
Snicolas

Reputation: 38168

You could use introspection on R.colors to find out all field names and the associated values.

R.colors.getClass().getFields() will give you the list of all colors.

Using getName()on each field will provide you with the list of all color names and getInt() will give you the value of each color .

Upvotes: 0

Orab&#238;g
Orab&#238;g

Reputation: 11992

I think you will have to move your color.xml file into the /asset directory. You will be obliged to parse the XML "by hand", and it won't be possible to use the R.color.* syntax. (unless you choose to duplicate the file)

Upvotes: 0

Related Questions