<?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?
解决方法 使用反射API它相当简单(我很久以前就有类似drawable-ID的问题),但是很多有经验的用户说,“对dalvik的反思真的很慢”,所以要警告!//Get all the declared fIElds (data-members):FIEld [] fIElds = R.color.class.getDeclaredFIElds();//Create arrays for color names and valuesString [] 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]);}总结
以上是内存溢出为你收集整理的android – 如何在不指定颜色名称或资源ID的情况下访问colors.xml(R.color.name)全部内容,希望文章能够帮你解决android – 如何在不指定颜色名称或资源ID的情况下访问colors.xml(R.color.name)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)