如何获得屏幕密度编程在android?
我的意思是:如何找到当前设备的屏幕dpi ?
如何获得屏幕密度编程在android?
我的意思是:如何找到当前设备的屏幕dpi ?
当前回答
试试这个:
DisplayMetrics dm = context.getResources().getDisplayMetrics();
int densityDpi = dm.densityDpi;
其他回答
试试这个…
在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
public static String getDensity(Context context) {
String r;
DisplayMetrics metrics = new DisplayMetrics();
if (!(context instanceof Activity)) {
r = "hdpi";
} else {
Activity activity = (Activity) context;
activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
if (metrics.densityDpi <= DisplayMetrics.DENSITY_LOW) {
r = "ldpi";
} else if (metrics.densityDpi <= DisplayMetrics.DENSITY_MEDIUM) {
r = "mdpi";
} else {
r = "hdpi";
}
}
return r;
}
另一个答案是:
/**
* @return "ldpi", "mdpi", "hdpi", "xhdpi", "xhdpi", "xxhdpi", "xxxhdpi", "tvdpi", or "unknown".
*/
public static String getDensityBucket(Resources resources) {
switch (resources.getDisplayMetrics().densityDpi) {
case DisplayMetrics.DENSITY_LOW:
return "ldpi";
case DisplayMetrics.DENSITY_MEDIUM:
return "mdpi";
case DisplayMetrics.DENSITY_HIGH:
return "hdpi";
case DisplayMetrics.DENSITY_XHIGH:
return "xhdpi";
case DisplayMetrics.DENSITY_XXHIGH:
return "xxhdpi";
case DisplayMetrics.DENSITY_XXXHIGH:
return "xxxhdpi";
case DisplayMetrics.DENSITY_TV:
return "tvdpi";
default:
return "unknown";
}
}
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和更高的级别上工作。
Blundell的回答是静态帮助方法:
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";
}