如何获得屏幕密度编程在android?
我的意思是:如何找到当前设备的屏幕dpi ?
如何获得屏幕密度编程在android?
我的意思是:如何找到当前设备的屏幕dpi ?
当前回答
这也是可行的:
getResources().getDisplayMetrics().density;
这将给你:
0.75 ldpi
1.0米
1.5 hdpi
2.0 - xhdpi
3.0 - xxhdpi
4.0 - xxxhdpi
裁判:密度
ref 2
其他回答
这也是可行的:
getResources().getDisplayMetrics().density;
这将给你:
0.75 ldpi
1.0米
1.5 hdpi
2.0 - xhdpi
3.0 - xxhdpi
4.0 - xxxhdpi
裁判:密度
ref 2
试试这个…
在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}"
}
}
你可以通过println("density: ${determineScreenDensityCode()}")调用 输出为System。输出:密度:xxxhdpi
试试这个:
DisplayMetrics dm = context.getResources().getDisplayMetrics();
int densityDpi = dm.densityDpi;
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;
}
这将在API级别4和更高的级别上工作。
另一种获得设备加载密度的方法:
为每个密度创建值文件夹
值(默认mdpi) values-hdpi values-xhdpi values-xxhdpi values-xxxhdpi
在它们各自的strings.xml中添加一个字符串资源:
<string name="screen_density">MDPI</string> <!-- ..\res\values\strings.xml -->
<string name="screen_density">HDPI</string> <!-- ..\res\values-hdpi\strings.xml -->
<string name="screen_density">XHDPI</string> <!-- ..\res\values-xhdpi\strings.xml -->
<string name="screen_density">XXHDPI</string> <!-- ..\res\values-xxhdpi\strings.xml -->
<string name="screen_density">XXXHDPI</string> <!-- ..\res\values-xxxhdpi\strings.xml -->
然后简单地获取字符串资源,你就有了密度:
String screenDensity = getResources().getString(R.string.screen_density);
如果密度大于XXXHDPI,它将默认为XXXHDPI,如果密度低于HDPI,它将默认为MDPI
我省略了LDPI,因为对于我的用例来说它是不必要的。