6
votes

How can I get the screen width dpi?

DisplayMetrics metrics = getResources().getDisplayMetrics();
int f = metrics.densityDpi;


  //  getWindowManager().getDefaultDisplay().getMetrics(metrics);

int width = metrics.widthPixels;
int dp = (int)(width / (metrics.density));

I do this, so lets assume my densitydpi is 120..and widthpixel 240.. via calculation i get 240/0.75.... so I have 320 widthdpi?

However that's not the case....widthdpi is smaller then 320 I think...because 320 goes with me wrong in the screen.... using 120 works.

on Nexus 4...with width 768 and densitydpi 320...I divide 768/2 and i get 384 correct width density dpi (it works)

But on other ones like 240, 160, 120 density dpi..the calculation of width dpi seems wrong ...

1
there is something i add. for example in the above case... if i do layout_margin 20 dp...and i deduct 40 from 320...i should get 280..but i get sthg like 240 ... so widthdpi is calculated wronguser3278732
For most apps, there's no reason to calculate these values, assuming you are writing a layout and using dp values all along (which will automatically scale things correctly no matter what density display the device has).ianhanniballake

1 Answers

13
votes

Per the Supporting Multiple Screens guide's definition of DP

px = dp * (dpi / 160)

Therefore

dp = px / (dpi / 160)

or equivalently

dp = px * 160 / dpi

Remember that dp stands for 'density-independent pixel' - i.e., 1dp is the same physical size on a ldpi device as it is on an xxhdpi device. Therefore you should expect all phones to have roughly ~300-400dp of width, noting the bucket sizes by dp:

  • xlarge screens are at least 960dp x 720dp
  • large screens are at least 640dp x 480dp
  • normal screens are at least 470dp x 320dp
  • small screens are at least 426dp x 320dp