Skip to content

Instantly share code, notes, and snippets.

@FoxIvan
Last active December 7, 2016 09:12
Show Gist options
  • Save FoxIvan/0b2450bfdef67348f438f8df9b92c548 to your computer and use it in GitHub Desktop.
Save FoxIvan/0b2450bfdef67348f438f8df9b92c548 to your computer and use it in GitHub Desktop.
Switch dimen value between different units
public class DensityUtil {
public static int dp2px(Context context, float dpVal) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
dpVal, context.getResources().getDisplayMetrics());
}
public static int sp2px(Context context, float spVal) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
spVal, context.getResources().getDisplayMetrics());
}
public static float px2dp(Context context, float pxVal) {
return (pxVal / context.getResources().getDisplayMetrics().density);
}
public static float px2sp(Context context, float pxVal) {
return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment