Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Android convert dp to px and vice versa
public static float convertPixelsToDp(float px){
DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
float dp = px / (metrics.densityDpi / 160f);
return Math.round(dp);
public static float convertDpToPixel(float dp){
DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
float px = dp * (metrics.densityDpi / 160f);
return Math.round(px);
//The above method results accurate method compared to below methods
private int convertDpToPx(int dp){
return Math.round(dp*(getResources().getDisplayMetrics().xdpi/DisplayMetrics.DENSITY_DEFAULT));
private int convertPxToDp(int px){
return Math.round(px/(Resources.getSystem().getDisplayMetrics().xdpi/DisplayMetrics.DENSITY_DEFAULT));

This comment has been minimized.

Copy link

@rishadbaniya rishadbaniya commented Jan 4, 2021


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment