Android resource not found because of width and height

前端 未结 1 1608
情话喂你
情话喂你 2021-02-06 08:42

I\'ve published an Android app in the store recently that worked perfectly for almost all of my users. However, I shortly started getting a few crash reports a week with the fol

1条回答
  •  北恋
    北恋 (楼主)
    2021-02-06 08:58

    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:

    
    
    
        
    
    

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

    0 讨论(0)
提交回复
热议问题