1

I am able to find the screen width using getWindowManager().getDefaultDisplay(). Now I want to know how can I get value in dp from the value that I got which is in pixel. For example, suppose I got a width of the screen using this code:

Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();

Now the width I got is in pixel, how do I convert it into dp.

Please help me to solve this out. I have seen in the android documentation but don't get to know how to implement it.

iknow
  • 8,358
  • 12
  • 41
  • 68
AndroidDev
  • 4,521
  • 24
  • 78
  • 126
  • 1
    possible duplicate of [converting pixels to dp in android](http://stackoverflow.com/questions/4605527/converting-pixels-to-dp-in-android) – Paresh Mayani Apr 26 '12 at 11:04
  • @PareshMayani I have used the following formula for getting dp values from pixels. Can u please check it whether the formula is right or not int widthDPI = (int) (screenWidthPx / (logicalDensity + 0.5)); – AndroidDev Apr 26 '12 at 11:48

4 Answers4

2

If you want to convert dp values to pixels u can use following formula:

DisplayMetrics metrics = getWindowManager().getDefaultDisplay().getMetrics(metrics);
float logicalDensity = metrics.density;
int px = (int) (dp * logicalDensity + 0.5);

To get dp from pixels, divide the density into the pixel value rather than multiply.

ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
2

For example: create new dimens.xml in your res/values folder:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="dim_5dp">5dp</dimen>
</resources>

Then in your activity:

int pixels = getResources().getDimensionPixelSize(R.dimen.dim_5dp);

The benefit is getDimensionPixelSize() takes care of zero-size, it returns at least 1 pixel in that case.

1

you need to use pixel density of your screen to convert between actual pixels and dp. This is described in Android developer portal/guide here. Take a look

binW
  • 13,220
  • 11
  • 56
  • 69
0

The shortest way is to use TypedValue.

  public static float pxToDp(Context context, float pixel) {
            return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, pixel, context.getResources().getDisplayMetrics());
  }
Rasoul Miri
  • 11,234
  • 1
  • 68
  • 78