How to get screen width in inches in ANDROID?

How to get screen width ??

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 let's assume that my density is 120..and the pixel width is 240 .. through the calculation, I get 240 / 0.75 .... so do I have 320 widthdpi?

However, this is not the case .... the widthdpi is less than 320, I think ... because 320 goes wrong with me on the screen .... using 120 works.

on Nexus 4 ... with a width of 768 and a density of dpi 320 ... I divide 768/2 and get 384 of the correct density dpi (works)

But on others, such as 240, 160, 120 dpi ... calculating the dpi width seems wrong ...

+6
source share
1 answer

The multi-screen support defines the definition of DP

 px = dp * (dpi / 160) 

therefore

 dp = px / (dpi / 160) 

or equivalent

 dp = px * 160 / dpi 

Remember that dp means β€œdensity independent pixel,” that is, 1dp is the same physical size on the ldpi device as on the xxhdpi device. Therefore, you should expect that all phones will have approximately ~ 300-400dp width, noting the dimensions of the dp bucket:

  • xlarge screens at least 960dp x 720dp
  • large screens of at least 640dp x 480dp
  • regular screens at least 470dp x 320dp
  • small screens at least 426dp x 320dp
+13
source

All Articles