资源不是可绘制对象

Resource is not a Drawable

此代码导致模拟器强制关闭异常(API 18)并在 ASUS Nexus 7 中工作(API 21)

<View
    android:layout_width="400dp"
    android:layout_height="2dp"
    android:layout_marginTop="30dp"
    android:background="@color/light_gray" />

如果我将 @color/light_gray 替换为 #EBEBEB,则在两个设备上都能完美运行。

例外是

Caused by: android.content.res.Resources$NotFoundException: Resource is not a Drawable (color or path): TypedValue{t=0x1/d=0x7f080060 a=-1 r=0x7f080060}

所以我在下面的代码中移动到 drawable,

<Button
    android:layout_width="wrap_content"
    android:layout_marginTop="30dp"
    android:layout_height="wrap_content"
    android:ems="10"
    android:background="@drawable/login_btn_selector"
    android:text="Login"
    android:id="@+id/btnLogin" />

这个抛出以下异常,

 Caused by: android.content.res.Resources$NotFoundException: File res/drawable-hdpi-v4/login_btn_selected.xml from drawable resource ID #0x7f020095

所以我尝试将 login_btn_selected.xml 放在 res/drawable-hdpi-v4/ 文件夹中,然后它说 res/drawable-hdpi/res/drawable-hdpi-v4/ 之间出现重复文件,所以我将其从 res/drawable-hdpi/,然后在 v4 文件夹中再次找不到相同的资源异常,

Caused by: android.content.res.Resources$NotFoundException: File res/drawable-hdpi-v4/login_btn_selected.xml from drawable resource ID #0x7f020095

所以我终于来到了SO

问题是,

  1. 我想知道这个问题是只在模拟器上还是在真实设备上也有。

  2. 如果在真实设备中也意味着我该如何克服这个问题?

    我想使用 @color/light_gray 而不是硬编码,我还想使用可绘制选择器。

注意:我已经删除并重新创建了模拟器,没有用。我也在 API 19 模拟器上测试过,同样的问题。

任何解决方案都将受到高度赞赏。

我认为最好的方法是,首先在 "drawable" 文件夹中创建一个 xml 文件,然后执行如下操作。

例如light_gray.xml 然后执行如下操作。

<?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
        <solid android:color="@color/light_gray" />
    </shape>

保存后。

像下面这样更改您的代码。

<View
    android:layout_width="400dp"
    android:layout_height="2dp"
    android:layout_marginTop="30dp"
    android:background="@ drawable/light_gray" />

但请务必将文件 light_gray.xml 仅放入 "drawable" 文件夹。不要把同一个文件放到"drawable-hdpi or drawable-hdpi-v4 and so on"

您的颜色资源必须位于 Android 资源文件中(即:在 colors.xml 文件中)。
Android 不会抱怨 where 你设置它,但它 必须 被定义为 color 资源 .

即:

<color name="light_gray">#ebebeb</color>

[编辑]

名称似乎不匹配...
看到这一行:

android:background="@drawable/login_btn_selector"

那你说:So I tried to place the login_btn_selected.xml.

好像是

的原因
Caused by: android.content.res.Resources$NotFoundException: File res/drawable-hdpi-v4/login_btn_selected.xml from drawable resource ID #0x7f020095.

因为我的颜色资源文件在\res\values-21文件夹下,现在把它移到\res\values\文件夹下,现在应用程序可以正常使用了。谢谢各位朋友

还要确保您没有将 imageView 的背景设置为 selectableItemBackgroundBorderless,否则旧设备会出现此错误:

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="?android:selectableItemBackgroundBorderless" />

我在最近制作的应用程序中遇到了同样的问题。就我而言,问题是我将一张图片放在名为 drawable-v21 的文件夹中,该文件夹在旧版 android API.

中不可用

解决方案是将您的 drawable 也放在 drawable-...dpi 文件夹中。