getting the screen density programmatically in and

2018-12-31 04:35发布

How to get the screen density programmatically in android?

I mean: How to find the screen dpi of the current device?

16条回答
谁念西风独自凉
2楼-- · 2018-12-31 04:57
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.

查看更多
ら面具成の殇う
3楼-- · 2018-12-31 05:02

If you want to retrieve the density from a Service it works like this:

WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics metrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(metrics);
查看更多
宁负流年不负卿
4楼-- · 2018-12-31 05:03

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";
}
查看更多
荒废的爱情
5楼-- · 2018-12-31 05:04

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

enter image description here

ref: density

查看更多
浅入江南
6楼-- · 2018-12-31 05:04

The following answer is a small improvement based upon qwertzguy's answer.

double density = getResources().getDisplayMetrics().density;
if (density >= 4.0) {
   //"xxxhdpi";
}
else if (density >= 3.0 && density < 4.0) {
   //xxhdpi
}
else if (density >= 2.0) {
   //xhdpi
}
else if (density >= 1.5 && density < 2.0) {
   //hdpi
}
else if (density >= 1.0 && density < 1.5) {
   //mdpi
}
查看更多
刘海飞了
7楼-- · 2018-12-31 05:04

Try this...

In kotlin

fun determineScreenDensityCode(): String {
      return when (resources.displayMetrics.densityDpi) {
         DisplayMetrics.DENSITY_LOW -> "ldpi"
         DisplayMetrics.DENSITY_MEDIUM -> "mdpi"
         DisplayMetrics.DENSITY_HIGH -> "hdpi"
         DisplayMetrics.DENSITY_XHIGH, DisplayMetrics.DENSITY_280 -> "xhdpi"
         DisplayMetrics.DENSITY_XXHIGH, DisplayMetrics.DENSITY_360, DisplayMetrics.DENSITY_400, DisplayMetrics.DENSITY_420 -> "xxhdpi"
         DisplayMetrics.DENSITY_XXXHIGH, DisplayMetrics.DENSITY_560 -> "xxxhdpi"
         else -> "Unknown code ${resources.displayMetrics.densityDpi}"
     }
}

You can call by println("density: ${determineScreenDensityCode()}") and the output will be System.out: density: xxxhdpi

查看更多
登录 后发表回答