首页 > 解决方案 > 无法在可绘制对象中使用主题属性。得到 android.content.res.Resources$NotFoundException 错误

问题描述

我得到了以下可绘制的形状:

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
    <solid android:color="#222222" />
    <stroke android:width="1dip" android:color="?attr/colorPrimary"/>
    <corners
        android:topLeftRadius="58dp"
        android:topRightRadius="58dp"
        android:bottomRightRadius="58dp"
        android:bottomLeftRadius="58dp">
    </corners>
    <padding
        android:left="4dp"
        android:top="4dp"
        android:right="4dp"
        android:bottom="4dp" />
</shape>

我在这一行中从我的主题设置颜色属性:

<stroke android:width="1dip" android:color="?attr/colorPrimary"/>

项目编译正常,没有任何问题,但是在设备上运行时我遇到了以下问题:

    android.view.InflateException: Binary XML file line #119: Error inflating class TextView
    ...
    Caused by: android.content.res.Resources$NotFoundException: File
 res/drawable/bordered_green_solid_textview.xml from drawable resource ID #0x7f07006a

当我替换?attr/colorPrimary并使用例如#222222之类的十六进制颜色时,它将毫无问题地运行。

我应该怎么做才能在我的可绘制对象中使用?attrs而不会出现问题?

PS:我的最低 API 级别 19

我的文本视图

<TextView android:id="@+id/imagesCounter"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_marginLeft="35dp"
            android:layout_marginBottom="35dp"
            android:background="@drawable/bordered_green_solid_textview"
            android:gravity="center"
            android:text="16"
            android:textColor="?attr/colorPrimary"
            android:textSize="9sp"
            app:layout_constraintBottom_toBottomOf="@+id/imageBorder"
            app:layout_constraintStart_toStartOf="@+id/imageBorder"
            tools:text="67" />

标签: androidstylesthemesandroid-drawable

解决方案


您不能在drawable下面的 XML 中引用属性API 21.

尝试更换

<stroke android:color="?attr/colorPrimary" />

<stroke android:color="@color/colorPrimary" />

推荐阅读