getting the screen density programmatically in android?
How to get the screen density programmatically in android?
I mean: How to find the screen dpi of the current device?
Solution 1:
You can get info on the display from the DisplayMetrics struct:
DisplayMetrics metrics = getResources().getDisplayMetrics();
Though Android doesn't use a direct pixel mapping, it uses a handful of quantized Density Independent Pixel values then scales to the actual screen size. So the metrics.densityDpi
property will be one of the DENSITY_xxx
constants (120
, 160
, 213
, 240
, 320
, 480
or 640
dpi).
If you need the actual lcd pixel density (perhaps for an OpenGL app) you can get it from the metrics.xdpi
and metrics.ydpi
properties for horizontal and vertical density respectively.
If you are targeting API Levels earlier than 4. The metrics.density
property is a floating point scaling factor from the reference density (160dpi). The same value now provided by metrics.densityDpi
can be calculated
int densityDpi = (int)(metrics.density * 160f);
Solution 2:
This also works:
getResources().getDisplayMetrics().density;
This will give you:
0.75 - ldpi
1.0 - mdpi
1.5 - hdpi
2.0 - xhdpi
3.0 - xxhdpi
4.0 - xxxhdpi
ref: density
ref 2
Solution 3:
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
switch(metrics.densityDpi) {
case DisplayMetrics.DENSITY_LOW:
break;
case DisplayMetrics.DENSITY_MEDIUM:
break;
case DisplayMetrics.DENSITY_HIGH:
break;
}
This will work on API level 4 and higher.
Solution 4:
Blundell's answer as a static helper method:
private static String getDensityName(Context context) {
float density = context.getResources().getDisplayMetrics().density;
if (density >= 4.0) {
return "xxxhdpi";
}
if (density >= 3.0) {
return "xxhdpi";
}
if (density >= 2.0) {
return "xhdpi";
}
if (density >= 1.5) {
return "hdpi";
}
if (density >= 1.0) {
return "mdpi";
}
return "ldpi";
}