不能在drawable中使用引用的颜色(按主题)

问题描述 投票:4回答:2

考虑:

styles.xml

<style name="BlueTheme" parent="@android:style/Theme.Black.NoTitleBar">
    <item name="theme_color">@color/theme_color_blue</item>
</style>

attrs.xml

<attr name="theme_color" format="reference" />

color.xml

<color name="theme_color_blue">#ff0071d3</color>

最后是drawable progress_bar.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item android:id="@android:id/background">
        <shape>
            <stroke
                android:width="2px"
                android:color="#ff515151" />

            <solid android:color="@color/transparent" />
        </shape>
    </item>
    <item android:id="@android:id/progress">
        <clip>
            <shape>
                <solid android:color="?attr/theme_color" />
            </shape>
        </clip>
    </item>

</layer-list>

当使用进度条drawable时:

<ProgressBar
    android:id="@+id/progressBarStartup"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:progressDrawable="@drawable/progress_bar"
    android:visibility="visible" />

我收到运行时错误。看来Android无法获得色彩主题。

06-24 16:35:57.032: E/AndroidRuntime(3493): java.lang.RuntimeException: Unable to start activity ComponentInfo{xxx.xxx.activities.startup.ActivityStartup}: android.view.InflateException: Binary XML file line #33: Error inflating class android.widget.ProgressBar


06-24 16:45:32.265: E/AndroidRuntime(9901): Caused by: android.content.res.Resources$NotFoundException: Resource is not a Drawable (color or path): TypedValue{t=0x2/d=0x7f010000 a=-1}
android android-resources android-theme
2个回答
3
投票

是的,这似乎是一个已知的问题。但有一个解决方法。不要像你描述的那样使用?attr引用的颜色,而是创建几个drawable(尽可能多的颜色),让每个颜色直接调用它们的颜色。在主题级别,根据主题引用drawables本身。它的工作方式。

更新:

在Lollipop上,您可以使用XML对drawable进行着色。要覆盖前Lollipop,您可以简单地为所有相关的drawables调用它(感谢appcompat库的新版本):

public void setDrawableColor(Drawable d, int color) {
  if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
    d = DrawableCompat.wrap(d);
    DrawableCompat.setTint(d.mutate(), color);
  }
}

0
投票

你应该使用<attr name="theme_color" format="integer"/>

© www.soinside.com 2019 - 2024. All rights reserved.