Since Android API Level 15 there is the method public Drawable getDrawableForDensity (int id, int density)
to retrieve a drawable object for a specific screen density. Is there any way to do this prior to API Level 15?

- 1,248
- 2
- 12
- 23
-
3Not trying to be dense, but why can't you just fetch the Drawable by its bare name (resource ID) and let the OS figure out the right one? – Sparky Feb 20 '12 at 10:36
-
1That works fine for my XML layouts, but when I load the bitmap via BitmapFactory.decodeResource(Resources res, int id) it shows the bitmap with a smaller resolution. Maybe that has to do with some scaling the BitmapFactory does, therefore I wanted to make sure it is loading the proper resource. Anyway, when drawing to a canvas it could be useful to have access to other resolutions of the bitmap, without including it multiple times in the APK. – Arthur Dent Feb 20 '12 at 11:17
-
That is true, but then if you want to be lazy, you can just include it once and let the OS figure out there aren't any other copies. You can probably get away with only MDPI or HDPI for a photo; line art won't look so good. – Sparky Feb 20 '12 at 21:42
-
Possibly relevant prior discussion: http://stackoverflow.com/questions/7793031/is-it-possible-to-access-a-drawable-from-a-specific-density-in-android – Sparky Feb 20 '12 at 21:46
-
It may be possible to reverse engineer the method from the Android source: https://android.googlesource.com/platform/frameworks/base/+/d922ae01ca99a2b6d39a9393f86776a1d10ebd14/core/java/android/content/res/Resources.java – Alex Tennant Feb 18 '14 at 14:38
-
this might help you http://stackoverflow.com/a/18387344/951045 – techieWings Feb 21 '14 at 10:12
1 Answers
So I actually thought it could be resolved using reverse-engineering of Android APIs and the source-code as per @adtennant's suggestion. I started writing the solution it, but in the process hit a dead end as an underlying native (non-Java) API that is necessary is unavailable in later versions of Android.
If you are okay constraining this to just Bitmaps, as implied by your comment, it is possible to do this with BitmapFactory as suggested. BitmapFactory has another method:
decodeResource(Resources res, int id, BitmapFactory.Options opts)
This method accepts the additional BitmapFactory.Options which will allow you to specify the density to load. This appears to have existed since API level 1. Specifically, I believe that you can use:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inDensity = DisplayMetrics.DENSITY_MEDIUM; // whichever you want to load
options.inTargetDensity = getResources().getDisplayMetrics().densityDpi;
options.inScaled = true;
This will also scale it to the screen density if a mismatched density is loaded.

- 3,631
- 32
- 31