从R.color检索颜色编程 [英] Retrieve color programmatically from R.color
问题描述
我有一个包含许多TextViews,一个TextView的应包含根据所检索到的数据的不同的背景颜色一个ListView。
I have a ListView which contains many TextViews, and one TextView should contain a different background color depending on the data that is retrieved.
由于我不想硬$ C C I用于R.color设置我的色彩的颜色。这工作不错,但我必须手动检查每一种颜色,因为我注意到能够得到的颜色像一个HashMap中。所以,我的第一次尝试是这样的:
Because i dont want to hardcode the colors i used R.color to set my Colors. That works nice, but i have to check manually for every color, because i am note able to get the colors like an HashMap. So my first Try was this:
switch(line) {
case "1":
lineColor = context.getResources().getColor(R.color.line1);
case "2":
lineColor = context.getResources().getColor(R.color.line2);
....
....
}
这似乎远离清洁code,所以我尝试了不同的方法使用字符串数组:
This seems far away from clean code, so i tried a different approach by using String-Arrays:
<string-array name="line_color_names">
<item>1</item>
<item>2</item>
....
</string-array>
<string-array name="line_color_values">
<item>#e00023</item>
<item>#ef9ec1</item>
....
</string-array>
在我AdapterClass我刚刚创建了一个HashMap中,并把这个字符串数组在一起:
In my AdapterClass i just created a HashMap and put this String-Arrays together:
String[] line_color_names = context.getResources().getStringArray(
R.array.line_color_names);
String[] line_color_values = context.getResources().getStringArray(
R.array.line_color_values);
lineColors = new HashMap<String, String>();
for (int i = 0; i < line_color_names.length; i++) {
lineColors.put(line_color_names[i], line_color_values[i]);
}
所以我的问题是:这是实现这一目标的唯一途径,或有另一种,最好通过直接从R.color服用颜色
So my Question is: Is this the only way to achieve this or is there another, ideally by taking colors directly from R.color?
在此先感谢!
推荐答案
您可以通过使用资源名称取色ID( R.color.foo
),并在解决问题运行时间:
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;
}
然后
int colorId = getColorIdByResourceName("foo21");
int colorVal = getResources().getColor(getColorIdByResourceName("foo21"));
这篇关于从R.color检索颜色编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!