(@Arash's answer provides a workaround, but this is my attempt to explain why it may work.)
So you have a rather big image in the drawable
resource directory, you reference it in your layout xml file, and get an out of memory error at runtime when inflating it.
When loading drawable resources, Android will perform some pre-scaling if it deems it necessary. From the official documentation:
Based on the density of the current screen, the system uses any size- or density-specific resources from your application and displays them without scaling. If resources are not available in the correct density, the system loads the default resources and scales them up or down as needed to match the current screen's density. The system assumes that default resources (those from a directory without configuration qualifiers) are designed for the baseline screen density (mdpi), unless they are loaded from a density-specific resource directory.
This means 2 things:
- If there's no resource of the density of the environment the application is currently running on, the system will take a resource of another density and scale it (up or down) to match the target density
- Resources put in the
drawable
directory are assumed to be targeting an mdpi
density
So you're currently running on an xxhdpi phone. The system wants to load the learn_more
drawable resource to paint it on the ivLearnMore
widget. It will look for it in the drawable-xxhdpi
in priority but won't find it there, so will take the closest one it finds, in this case the one in the drawable
directory (which it assumes to be targeting mdpi density), and load it into memory scaling it by a factor of 3 which is a lot if your image file was significantly big and can easily require more memory than is available to the application (and cause an out of memory error).
This is also why it loaded fine on your old crappy 2.3 device: the device was most likely of mdpi or hdpi density and the system didn't try to upscale it or did it by a factor of only 1.5.
The main thing here being that you put a resource suitable for an xxhdpi (or more ?) density in an mdpi directory.
So you have several options:
- provide one resource appropriately sized per density (i.e. one in each
drawable-*
directory): this is the best to avoid any problem, when possible
- if you only have one version of the resource, put it in the directory matching its density (
drawable
being equivalent to drawable-mdpi
!), in your case maybe drawable-xxhdpi
(depends on your resource)
- put the resource in the
drawable-nodpi
directory, this will prevent the system from performing any pre-scaling of the resource (but this is typically for density-agnostic resources e.g. which you resize yourself at runtime)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…