【问题标题】:how to access colors.xml without specifying color name or resource ID (R.color.name)如何在不指定颜色名称或资源 ID (R.color.name) 的情况下访问 colors.xml
【发布时间】:2012-08-21 11:13:24
【问题描述】:

包含颜色名称和十六进制代码的 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>

我可以使用以下语法访问特定颜色:

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

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

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

如何将整个 xml 文件中的颜色读入颜色名称的 String[] 和颜色资源的 int[](例如,R.color.Navy),而无需指定每个颜色名称或资源 ID ?

【问题讨论】:

    标签: android xml colors


    【解决方案1】:

    使用反射 API 相当简单(不久前我在 drawable-ids 上遇到过类似的问题),但是很多更有经验的用户说,“在 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 */ 
    }
    

    如果你有这些数组,那么你可以从它们创建一个 Map 以便于访问:

    Map<String, Integer> colors = new HashMap<String, Integer>();
    
    for(int i=0; i<hexColors.length; i++) {
        colors.put(colorNames[i], hexColors[i]);
    }
    

    【讨论】:

    • 工作就像一个魅力。谢谢你,@bali182。迈克 R.
    【解决方案2】:

    您可以在R.colors 上使用自省来找出所有字段名称和相关值。

    R.colors.getClass().getFields() 将为您提供所有颜色的列表。

    在每个字段上使用 getName() 将为您提供所有颜色名称的列表,getInt() 将为您提供每种颜色的值。

    【讨论】:

    • 您还应该考虑一种更精细的机制来区分向用户显示的颜色的名称(它们应该存储为字符串strings.xml)并将它们的值与颜色相关联(在colors.xml中)。
    【解决方案3】:

    我认为您必须将 color.xml 文件移动到 /asset 目录中。您将不得不“手动”解析 XML,并且无法使用 R.color.* 语法。 (除非您选择复制文件)

    【讨论】:

      猜你喜欢
      • 2011-09-28
      • 2014-03-17
      • 2019-05-11
      • 2023-02-04
      • 1970-01-01
      • 1970-01-01
      • 2021-11-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多