【问题标题】:How to extract color values (#rgb) from an Android theme?如何从 Android 主题中提取颜色值(#rgb)?
【发布时间】:2011-02-19 01:59:37
【问题描述】:

我想使用主题中的颜色将其应用于我的应用正在呈现的某些 HTML。我想知道我是否可以这样做?

我希望使用在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。

我需要在这里再跳几圈来解决实际颜色吗?我的初衷真的有用吗?也许它不起作用,因为颜色可以是任意的可绘制对象?

我没有找到任何相关文档,但如果你知道的话,请指点我那里。

顺便说一句。我也尝试了obtainStyledAttributes(),但这基本上有同样的问题。

【问题讨论】:

  • This answer 展示了如何将颜色 int 转换回其十六进制字符串。

标签: android themes


【解决方案1】:

我认为您应该将 colorResourceId 重命名为 myColor 或类似名称,因为据我所知,这就是您的代码中应该包含的内容。

-16777216 相当于 0xFF000000,即黑色,因此您的主题可能是白色背景上的黑色文本。

【讨论】:

    猜你喜欢
    • 2017-05-15
    • 1970-01-01
    • 1970-01-01
    • 2014-06-21
    • 1970-01-01
    • 2013-12-02
    • 2016-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多