Android – why does the screen always have the wrong inch size?
•
Android
I want to calculate the device size in inches. I'm using this code and it will appear every time I search. But the problem is that when I put a 4.5-inch device in Android studio, my answer is 4. I tried a 5.2-inch device, and then got 4.3-inch and 10.1-inch - > the answer is 9.0. So how do I get an accurate answer?
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
double wi=(double)dm.widthPixels/dm.xdpi;
double hi=(double)dm.heightPixels/dm.ydpi;
double x = Math.pow(wi,2);
double y = Math.pow(hi,2);
double screenInches = Math.sqrt(x+y);
Log.e("hello"," "+screenInches);
resolvent:
The problem with your code is that it is not taken into account
action bar
Soft key
Screen orientation
Use the following answers
WindowManager windowManager = getWindowManager();
Display display = windowManager.getDefaultDisplay();
DisplayMetrics displayMetrics = new DisplayMetrics();
display.getMetrics(displayMetrics);
// since SDK_INT = 1;
mWidthPixels = displayMetrics.widthPixels;
mHeightPixels = displayMetrics.heightPixels;
// includes window decorations (statusbar bar/menu bar)
if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17)
{
try
{
mWidthPixels = (Integer) Display.class.@R_419_1075@("getRawWidth").invoke(display);
mHeightPixels = (Integer) Display.class.@R_419_1075@("getRawHeight").invoke(display);
}
catch (Exception ignored)
{
}
}
// includes window decorations (statusbar bar/menu bar)
if (Build.VERSION.SDK_INT >= 17)
{
try
{
Point realSize = new Point();
Display.class.@R_419_1075@("getRealSize", Point.class).invoke(display, realSize);
mWidthPixels = realSize.x;
mHeightPixels = realSize.y;
}
catch (Exception ignored)
{
}
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
double x = Math.pow(mWidthPixels/dm.xdpi,2);
double y = Math.pow(mHeightPixels/dm.ydpi,2);
double screenInches = Math.sqrt(x+y);
Log.d("debug","Screen inches : " + screenInches);
Thanks to him
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码