Skip to content

Instantly share code, notes, and snippets.

@pythoncat1024
Created November 4, 2019 10:25
Show Gist options
  • Save pythoncat1024/2f6407acda4a2516c8fd6aa76ddf8302 to your computer and use it in GitHub Desktop.
Save pythoncat1024/2f6407acda4a2516c8fd6aa76ddf8302 to your computer and use it in GitHub Desktop.
dp2px,px2dp,sp2px,px2sp
public class ViewUtils {
private ViewUtils() {
}
public static String formatSpecMode(int mode) {
String format;
switch (mode) {
case View.MeasureSpec.EXACTLY:
format = "EXACTLY";
break;
case View.MeasureSpec.AT_MOST:
format = "AT_MOST";
break;
case View.MeasureSpec.UNSPECIFIED:
format = "UNSPECIFIED";
break;
default:
format = ">UNKNOWN_MODE " + mode + "<";
break;
}
return format;
}
public static String logMeasureSpec(int spec, String description) {
int mode = View.MeasureSpec.getMode(spec);
int size = View.MeasureSpec.getSize(spec);
String format = String.format(Locale.ENGLISH,
"onMeasure of %s: size=%s, mode=%s",
description, size, formatSpecMode(mode));
return format;
}
/**
* convert dp to its equivalent px
*/
public static float dp2px(Context context, int dp) {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
dp, context.getResources().getDisplayMetrics());
}
/**
* convert sp to its equivalent px
*/
public static float sp2px(Context context, int sp) {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
sp, context.getResources().getDisplayMetrics());
}
public static int px2sp(Context context, float pxValue) {
final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
return (int) (pxValue / fontScale + 0.5f);
}
public static int px2dp(Context context, float pxValue) {
final float fontScale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / fontScale + 0.5f);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment