2010-05-13 87 views
10

我想使用主题中的颜色将其应用于某些HTML应用正在呈现。我想知道我能否做到这一点?如何从Android主题中提取颜色值(#rgb)?

我期待像他们在指定的themes.xml使用颜色:

<item name="colorBackground">@android:color/background_dark</item> 
    <item name="textColorPrimary">@android:color/primary_text_dark</item> 

所以看着他们,他们都以同样的方式声明。所以我想我也可以用同样的方式访问它们。

这不是原因。当试图访问这些值是这样的:

TypedValue tv = new TypedValue(); 
    getTheme().resolveAttribute(android.R.attr.colorBackground, tv, true); 

    System.out.println("tv.string=" + tv.string); 
    System.out.println("tv.coerced=" + tv.coerceToString()); 

    int colorResourceId = getResources().getColor(tv.resourceId); 
    System.out.println("colorResourceId=" + colorResourceId); 

    tv = new TypedValue(); 
    getTheme().resolveAttribute(android.R.attr.textColorPrimary, tv, true); 

    System.out.println("tv.string=" + tv.string); 
    System.out.println("tv.coerced=" + tv.coerceToString()); 

    colorResourceId = getResources().getColor(tv.resourceId); 
    System.out.println("colorResourceId=" + colorResourceId); 

我得到这个结果:

I/System.out(1578): tv.string=null 
I/System.out(1578): tv.coerced=#ffffffff 
I/System.out(1578): colorResourceId=-1 

I/System.out(1578): tv.string=res/color/primary_text_light.xml 
I/System.out(1578): tv.coerced=res/color/primary_text_light.xml 
I/System.out(1578): colorResourceId=-16777216 

的结果是不同的。第一个实际上给我的颜色“#fffffff”,这将为我工作,第二个只给了我一个XML。

我是否需要在这里跳过更多的箍来解决实际的颜色?我的初衷是否有用?也许它不会工作,因为颜色可以是任意的drawables?

我没有找到任何相关文件,但如果你知道任何,请指出我那里请。

Btw。我也尝试了getsStyledAttributes(),但是这有基本相同的问题。

+0

[This answer](http://stackoverflow.com/a/6540378/15882)显示如何将颜色int转换回其十六进制字符串。 – 2016-03-04 17:48:00

回答

6

我想你应该重命名colorResourceIdmyColor或类似的东西,因为这就是它应该在你的代码中,据我所知。

-16777216相当于0xFF000000,这是黑色,所以可能你的主题是白色背景上的黑色文字。