How to calculate dp from pixels in android programmatically

Dawid Hyży picture Dawid Hyży · Nov 28, 2011 · Viewed 97.7k times · Source

I want to calculate dp from px programmatically. How to do it? I get resolution from:

DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
ht = displaymetrics.heightPixels;
wt = displaymetrics.widthPixels;

Answer

Vicky Chijwani picture Vicky Chijwani · Nov 13, 2013

All the answers here show a dp->px conversion rather than px->dp, which is what the OP asked for. Note that TypedValue.applyDimension cannot be used to convert px->dp, for that you must use the method described here: https://stackoverflow.com/a/17880012/504611 (quoted below for convenience).

Without Context object, elegant static methods:

public static int dpToPx(int dp) {
    return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
}

public static int pxToDp(int px) {
    return (int) (px / Resources.getSystem().getDisplayMetrics().density);
}