我最近在商店中发布了一款适用于几乎所有用户的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中视图的背景。
答案 0 :(得分:22)
这里的问题是由Android中可绘制资源的自动缩放和非常小的drawables的不幸组合引起的。
例如,如果您的应用仅提供drawable-xhpdi
资源,则需要缩小尺寸以适应较低密度的屏幕。如果您自己不提供这些资源,则由Android自动完成。
显示密度的大小设置如下:
这意味着您的xhdpi
资源在中密度显示屏上缩小了2.0倍。这可能会对质量产生不利影响,这就是为什么通常建议您自己创建和提供这些低密度资源的原因。
现在,回到手头的问题。拥有宽度或高度非常小(1或2像素)的资源并不罕见。用例的一个示例是为视图提供纯色背景。
不幸的是,当以xhdpi
提供这些资源并将其缩小时,像素大小可以被截断为0.没有适当的保护措施,Android将无法创建具有该维度和崩溃的Bitmap
有几种解决方案:
ldpi
中,然后将其放大,这不会影响作为背景的目的。nodpi
drawable中,永远不会缩放。最后一个选项最准确地描述了意图,并允许您稍后在没有图像编辑程序的情况下轻松更改颜色:
<?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
文件夹中,它始终可以正常运行。