Android:具有可绘制资源的 ImageButton 抛出 ResourceNotFoundException

Android: ImageButton with drawable resources throws ResourceNotFoundException

我正在尝试按照 this instruction 创建自己的按钮样式。所以我创建了两个可绘制对象(形状)。一种用于压制式,一种用于普通式。两者都只是推迟了颜色。

但是当我启动应用程序时,它崩溃并出现异常(见下文)。不知怎的,它找不到按钮资源。但是为什么?

这是可绘制的形状(button_rounded_pressed.xml 和 button_rounded_normal.xml):

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
    <solid android:color="?attr/colorPrimary" />
    <padding android:left="7dp"
             android:top="7dp"
             android:right="7dp"
             android:bottom="7dp" />
    <corners android:radius="8dp" />
</shape>

然后我创建了一个选择器button_rounded.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/button_rounded_pressed"
          android:state_pressed="true" />
    <item android:drawable="@drawable/button_rounded_normal" />
</selector>

然后像这样在 ImageButton 上使用这个 style/drawable/selector:

    <ImageButton
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:layout_alignParentTop="true"
            android:src="@mipmap/ic_launcher"
            android:background="@drawable/button_rounded"
            />

但是运行应用程序在扩充布局时抛出以下异常。

Caused by: android.content.res.Resources$NotFoundException: File res/drawable/button_rounded.xml from drawable resource ID #0x7f02003b at android.content.res.Resources.loadDrawable(Resources.java:1953) at android.content.res.TypedArray.getDrawable(TypedArray.java:601) at android.view.View.(View.java:3328)

注意:您可以访问我的代码via GitHub

我敢打赌您正在 Lollipop 之前的设备上进行测试。您需要删除 colorPrimary 属性。

编辑: 根据 this 错误报告,直到 Lollipop 才支持在可绘制对象中引用主题属性。