前言
移动项目需要根据设备进行适配,这个还是很有用的,摘抄于此,方便自己查阅。
正文
public class DensityUtil { public static int dip2px(float dpValue) { return (int) (dpValue * Resources.getSystem().getDisplayMetrics().density + 0.5f * (float) (dpValue >= 0.0f ? 1 : -1)); } public static int dimenDip2px(int dimenId) { return dip2px(Resources.getSystem().getDimension(dimenId) / Resources.getSystem().getDisplayMetrics().density); } public static int px2dip(float pxValue) { return (int) (pxValue / Resources.getSystem().getDisplayMetrics().density + 0.5f * (float) (pxValue >= 0.0f ? 1 : -1)); } public static int px2sp(float pxValue) { return (int) (pxValue / Resources.getSystem().getDisplayMetrics().scaledDensity + 0.5f * (float) (pxValue >= 0.0f ? 1 : -1)); } public static int sp2px(float spValue) { return (int) (spValue * Resources.getSystem().getDisplayMetrics().scaledDensity + 0.5f * (float) (spValue >= 0.0f ? 1 : -1)); }}

