How to calculate dp from pixels in android programmatically

AndroidAndroid LayoutResolution

Android Problem Overview


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;

    

Android Solutions


Solution 1 - Android

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).

fun Context.dpToPx(dp: Int): Int {
    return (dp * resources.displayMetrics.density).toInt()
}

fun Context.pxToDp(px: Int): Int {
    return (px / resources.displayMetrics.density).toInt()
}

Solution 2 - Android

float ht_px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, ht, getResources().getDisplayMetrics());
float wt_px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, wt, getResources().getDisplayMetrics());

Solution 3 - Android

This should give you the conversion pixels -> dp:

DisplayMetrics displaymetrics = new DisplayMetrics();
int dp = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, myPixels, displaymetrics );

Solution 4 - Android

DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        String str_ScreenSize = "The Android Screen is: "
                    + dm.widthPixels
                    + " x "
                    + dm.heightPixels;

        TextView mScreenSize = (TextView) findViewById(R.id.strScreenSize);
        mScreenSize.setText(str_ScreenSize);

can u cheeck it out..

or this may also help u

int value = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 
                     (float) 123.4, getResources().getDisplayMetrics());

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDawid HyżyView Question on Stackoverflow
Solution 1 - AndroidVicky ChijwaniView Answer on Stackoverflow
Solution 2 - AndroidVladimirView Answer on Stackoverflow
Solution 3 - AndroidkaspermoerchView Answer on Stackoverflow
Solution 4 - AndroidNikhilReddyView Answer on Stackoverflow