【问题标题】:Android resource not found because of width and height由于宽度和高度,未找到 Android 资源
【发布时间】:2013-03-03 22:24:17
【问题描述】:

我最近在商店中发布了一款 Android 应用,它几乎适用于我的所有用户。但是,我很快就开始每周收到一些崩溃报告,其中包含以下跟踪:

Caused by: android.content.res.Resources$NotFoundException: File res/drawable-xhdpi/dark_button_unpressed.png from drawable resource ID #0x7f02005d
at android.content.res.Resources.loadDrawable(Resources.java:1716)
at android.content.res.Resources.getDrawable(Resources.java:581)
at android.graphics.drawable.StateListDrawable.inflate(StateListDrawable.java:162)
at android.graphics.drawable.Drawable.createFromXmlInner(Drawable.java:787)
at android.graphics.drawable.Drawable.createFromXml(Drawable.java:728)
at android.content.res.Resources.loadDrawable(Resources.java:1696)
... 40 more
Caused by: java.lang.IllegalArgumentException: width and height must be > 0
at android.graphics.Bitmap.nativeCreate(Native Method)
at android.graphics.Bitmap.createBitmap(Bitmap.java:477)
at android.graphics.Bitmap.createBitmap(Bitmap.java:444)
at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:349)
at android.graphics.BitmapFactory.finishDecode(BitmapFactory.java:498)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:473)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:336)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:697)
at android.content.res.Resources.loadDrawable(Resources.java:1711)
... 45 more

要确定这里到底发生了什么并不容易。我可以从用户报告中收集到的唯一信息是,它似乎主要发生在具有低密度显示器的设备上。此特定资源用作 XML UI 中视图的背景。

【问题讨论】:

    标签: android android-resources forceclose


    【解决方案1】:

    这里的问题是由 Android 中可绘制资源的自动缩放和非常小的可绘制资源的不幸结合造成的。

    例如,如果您的应用仅提供 drawable-xhpdi 资源,则需要缩小它们的大小以适应较低密度的屏幕。如果您自己不提供这些资源,这将由 Android 自动完成。

    显示密度的比例设置如下:

    • xhdpi: 2.0
    • hdpi: 1.5
    • mdpi: 1.0
    • ldpi: 0.75

    这意味着您的 xhdpi 资源在中等密度显示器上按比例缩小了 2.0 倍。这可能不利于质量,因此通常建议您自己创建和提供这些密度较低的资源。

    现在,回到手头的问题。拥有非常小的宽度或高度(1 或 2 像素)的资源并不少见。一个用例示例是为视图提供纯色背景。

    不幸的是,当以xhdpi 提供这些资源并缩小它们时,像素大小可能会被截断为 0。对此没有任何保护措施,Android 将无法创建具有该尺寸的位图并崩溃。

    有几种解决方案:

    • 将资源包含为 ldpi 并改为放大,这不会影响作为背景的目的。
    • 将资源包含为nodpi drawable,它永远不会被缩放。
    • 改用 XML 资源。

    最后一个选项最准确地描述了意图,让您以后无需图像编辑程序即可轻松更改颜色:

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

    将此资源包含在drawables 文件夹中,它将始终正常工作。

    【讨论】:

    • @EladNava 很高兴我能帮助到别人:)
    • 很好的解决方案和很好的解释:D 这个问题花费了我太多时间:D 并且对于遇到这个问题的其他人,我建议将所有 9-patch 图像(通常是低图像)放入 drawables 文件夹中Overv 推荐 :)
    猜你喜欢
    • 2020-06-06
    • 2014-09-05
    • 1970-01-01
    • 1970-01-01
    • 2011-03-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-16
    • 1970-01-01
    相关资源
    最近更新 更多