Android resource not found because of width and height

て烟熏妆下的殇ゞ 提交于 2019-12-03 03:18:23

The problem here is caused by an unfortunate combination of the automatic scaling of drawable resources in Android and very small drawables.

If, for example, your app only provides drawable-xhpdi resources, they need to be downsized to fit lower density screens. This is done automatically by Android if you don't provide these resources yourself.

The scale of display densities is set to be like this:

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

That means that your xhdpi resources are scaled down by a factor 2.0 on medium density displays. This can be detrimental for the quality, which is why it is usually recommended to create and provide these lower density resources yourself.

Now, back to the problem at hand. It is not entirely uncommon to have a resource that has a very small width or height (1 or 2 pixels). An example of a use case is providing a solid color background for a view.

Unfortunately, when providing these resources as xhdpi and scaling them down, the pixel size can be truncated to 0. There is no guard in place for this and Android will fail to create a Bitmap with that dimension and crash.

There are several solutions for this:

  • Include the resource as ldpi and have it scale up instead, which doesn't affect the purpose as background.
  • Include the resource as nodpi drawable and it will never be scaled.
  • Use an XML resource instead.

The last option most accurately describes the intent and allows you to easily change the color later on without an image editing program:

<?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>

Include this resource in the drawables folder and it will always work properly.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!