我想按英寸计算设备尺寸。我正在使用此代码,每次搜索都会出现。但问题是当我把设备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);
答案 0 :(得分:2)
您的代码存在问题,因为它没有考虑到
<强>动作条强>
<强>软键强>
屏幕方向
使用以下答案
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);
归功于him
答案 1 :(得分:1)
您可以使用 getResources()。getDisplayMetrics()
DisplayMetrics:描述有关a的一般信息的结构 显示, 例如它的大小,密度和字体缩放。
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 returns incorrect screen size.
答案 2 :(得分:0)
设备尺寸与屏幕尺寸不同,因为屏幕不会覆盖设备总尺寸
Android操作系统与设备尺寸无关,您无法以编程方式获取设备尺寸,只能获得屏幕尺寸
答案 3 :(得分:0)
只需稍加改动即可尝试
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();
}