Android_IT
Android_IT

Reputation: 396

Android - PX to DP - Wrong height of layout

I am giving a layout height as 64dp in layout file and observed the mismatch in calculated and actual pixel height.

HDPI device - Calculated height - 96 pixels, Actual height: 102 pixels XXHDPI Device - Calculated height - 192 pixels, Actual height: 204 pixels

Any one can help me understand the difference in calculated and actual height.

Upvotes: 1

Views: 327

Answers (1)

s.d
s.d

Reputation: 29436

mdpi, hdpi, xhdpi etc are "generalized densities". That is, dpi groups or ranges.

From Android guide:

enter image description here

For example two devices can have dpi values of 310 and 320 dpi respectively and fall in same group: xhdpi.

The calculations done by device code are using exact dpi value. While calculations based on dpi groups assume the following:

  1. ldpi (low) ~120dpi
  2. mdpi (medium) ~160dpi
  3. hdpi (high) ~240dpi
  4. xhdpi (extra-high) ~320dpi
  5. xxhdpi (extra-extra-high) ~480dpi
  6. xxxhdpi (extra-extra-extra-high) ~640dpi

Update:

The following code:

int widthDp = 160;

Log.i("TEST", "Actual DPI: " + getResources().getDisplayMetrics().xdpi);

float widthDevice = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,widthDp,getResources().getDisplayMetrics());

Log.i("TEST", widthDp + " dip in pixels on device: " + widthDevice);

When run on two hdpi devices:

213 DPI device:

2164-2164/com.example.android.dpitest I/TEST﹕ Actual DPI: 213.0
2164-2164/com.example.android.dpitest I/TEST﹕ 160 dip in pixels on device: 213.0

And 240 DPI device:

2852-2852/com.example.android.dpitest I/TEST﹕ Actual DPI: 240.0
2852-2852/com.example.android.dpitest I/TEST﹕ 160 dip in pixels on device: 240.0

Upvotes: 2

Related Questions