Mik*_*keR 4 xml android colors
包含颜色名称和十六进制代码的XML文件随时可供Android程序员使用,例如:
<?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>
Run Code Online (Sandbox Code Playgroud)
我可以使用以下语法访问特定颜色:
TextView area1 = (TextView) findViewById(R.id.area);
area1.setBackgroundColor(Color.parseColor(getString(R.color.Navy)));
Run Code Online (Sandbox Code Playgroud)
要么
area1.setBackgroundColor(Color.parseColor("Navy"));
Run Code Online (Sandbox Code Playgroud)
要么
Resources res = getResources();
int rcol = res.getColor(R.color.Navy);
area1.setBackgroundColor(rcol);
Run Code Online (Sandbox Code Playgroud)
如何将整个xml文件中的颜色读入颜色名称的String []和颜色资源的int [](例如,R.color.Navy),而不必指定每个颜色名称或资源ID?
使用反射API它相当简单(我很久以前就有类似drawable-id的问题),但是很多有经验的用户说,"对dalvik的反思真的很慢",所以要警告!
//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 */
}
Run Code Online (Sandbox Code Playgroud)
然后,如果您有这些数组,那么您可以从它们创建一个Map以便于访问:
Map<String, Integer> colors = new HashMap<String, Integer>();
for(int i=0; i<hexColors.length; i++) {
colors.put(colorNames[i], hexColors[i]);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4768 次 |
| 最近记录: |