Get drawable for different screen density at runti

2019-08-15 02:46发布

问题:

I want to print sizes of all drawables at run-time. So if I am on hdpi device then I can print the size of hdpi drawables but how to get access to, lets say mdpi and xhdpi as well? I can get access to all drawables resource ids with following code:

final Class<R.drawable> c = R.drawable.class;
final Field[] fields = c.getDeclaredFields();

for (int i = 0, max = fields.length; i < max; i++) {
    final int resourceId;
    try {
        resourceId = fields[i].getInt(drawableResources);
    } catch (Exception e) {
        continue;
    }
    /* make use of resourceId for accessing Drawables here */
}

回答1:

Ok I found it, Basically you explicitly ask for a particular density drawable like this:

Drawable drawable = resources.getDrawableForDensity(id, DisplayMetrics.DENSITY_XHIGH);

or preferably this version

Drawable drawable = resources.getDrawableForDensity(id, DisplayMetrics.DENSITY_XHIGH, theme);