常用单位转换的工具类

public class DensityUtil {


private DensityUtil() {
/* cannot be instantiated */
throw new UnsupportedOperationException("cannot be instantiated");
}


/**
* dp----->px
*/
public static int dp2px(Context context, float dpVal) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
dpVal, context.getResources().getDisplayMetrics());
}


/**
* sp----->px
*/
public static int sp2px(Context context, float spVal) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
spVal, context.getResources().getDisplayMetrics());
}


/**
* px----->dp
*/
public static float px2dp(Context context, float pxVal) {
final float scale = context.getResources().getDisplayMetrics().density;
return (pxVal / scale);
}


/**
* px----->sp
*/
public static float px2sp(Context context, float pxVal) {
return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
}


}

你可能感兴趣的:(dp,px,SP,dip)