我想按英寸计算设备尺寸。我正在使用每个搜索都会出现的代码。但问题是当我把设备放在 4.5 英寸时,我在 android 工作室中的答案是 4。我尝试了 5.2 英寸设备,我也得到了 4.3 英寸以及 10.1 英寸 ->答案是 9.0。那么我怎样才能得到准确的答案呢?
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);
你的代码的问题在于它没有考虑到
操作栏
软键
屏幕方向
使用以下答案
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.getMethod("getRawWidth").invoke(display);
mHeightPixels = (Integer) Display.class.getMethod("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.getMethod("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);
功劳归于他
您可以使用 getResources((.getDisplayMetrics((
DisplayMetrics:描述有关 显示 例如它的大小、密度和字体缩放。
DisplayMetrics metrics = getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;
int dens = metrics.densityDpi;
double wi = (double)width / (double)dens;
double hi = (double)height / (double)dens;
double x = Math.pow(wi, 2);
double y = Math.pow(hi, 2);
double screenInches = Math.sqrt(x+y);
System.out.println("getSIZE"+screenInches);
有关更多信息,请访问 Android DisplayMetrics 返回不正确的屏幕尺寸。
设备尺寸与屏幕尺寸不同,因为屏幕不会覆盖整个设备尺寸
Android操作系统与设备尺寸无关,您无法以编程方式获取设备尺寸,您只能获得屏幕尺寸
只需稍作更改即可尝试此操作
DisplayMetrics metrics = getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;
int dens = metrics.densityDpi;
double wi = (double)width / (double)dens;
double hi = (double)height / (double)dens;
double x = Math.pow(wi, 2);
double y = Math.pow(hi, 2);
DecimalFormat df = new DecimalFormat("#.#");
df.setRoundingMode(RoundingMode.CEILING);
try {
double screenInches = Double.parseDouble(df.format(Math.sqrt(x+y)));
Log.e("hello"," "+screenInches);
} catch (NumberFormatException e) {
e.printStackTrace();
}