android - 无法在可绘制对象中使用引用颜色(按主题)

标签 android android-resources android-theme

考虑:

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>

当使用进度条绘制时:

<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}

最佳答案

是的,这似乎是一个已知问题。但是有一个解决方法。不要像您描述的那样使用 ?attr 引用颜色,而是创建多个可绘制对象(与您拥有的不同颜色一样多),让每个对象直接调用其颜色。在主题级别,根据主题引用可绘制对象本身。它以这种方式工作。

更新:

在 Lollipop 上,您可以使用 XML 为可绘制对象着色。为了覆盖 Lollipop 之前的版本,您可以简单地为所有有问题的可绘制对象调用它(感谢更新版本的 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);
  }
}

关于android - 无法在可绘制对象中使用引用颜色(按主题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17278244/

相关文章:

android - Android 上的 Parse.com API PHP 后端和本地存储

Android 在 hdpi 设备上缩放 hdpi 图像

android - 将自定义小部件样式添加到应用程序主题

android - 以编程方式设置 android :windowIsTranslucent

android - 通过字符串获取可绘制对象

android - Shape Drawable 参数取决于应用的样式

java - Android处理程序,不在ui线程中执行post()

java - 一个 ScrollView 只能有一个子 Android XML 文件

java - 无法使用不同的用户 ID 登录我的 Facebook 与 Android 应用程序集成

android - dimen.xml 还是dimen.xml?