Retrieve Color Programmatically From R.color
I have a ListView which contains many TextViews, and one TextView should contain a different background color depending on the data that is retrieved. Because i dont want to hardc
Solution 1:
You can get color ID by using resource name (R.color.foo
) and resolve it at runtime:
public int getColorIdByResourceName(String name) {
int color;
try {
Class res = R.color.class;
Field field = res.getField( name );
int color = field.getInt(null);
} catch ( Exception e ) {
e.printStackTrace();
}
return color;
}
and then
int colorId = getColorIdByResourceName("foo21");
int colorVal = getResources().getColor(getColorIdByResourceName("foo21"));
Solution 2:
Your second solution seems good and isn't a hack exactly. You should be find with this. But if you get your colour name dynamically then this code could be handy for you.
public static int getColorIDFromName(String name)
{
int colorID = 0;
if(name == null
|| name.equalsIgnoreCase("")
|| name.equalsIgnoreCase("null"))
{
return 0;
}
try
{
@SuppressWarnings("rawtypes")
Class res = R.color.class;
Field field = res.getField(name);
colorID = field.getInt(null);
}
catch(Exception e)
{
Log.e("getColorIDFromName", "Failed to get color id." + e);
}
return colorID;
}
Post a Comment for "Retrieve Color Programmatically From R.color"