在编写练手项目时,有一个获取屏幕高度的问题,要把两个组件固定显示在第一屏,
因此,获取屏幕的高度是这里必须跨过的坎。
首先,我们需要明确,一个应用程序的显示分为哪些范围呢,这里我就不解释了
给出一篇相当清晰的参考文章,感谢作者。
https://blog.csdn.net/a_running_wolf/article/details/50477965
经过我查阅资料,得出一下六种方法,我写了一个demo,在onCreate方法调用下面的方法并输出结果即可。
其中部分方法是参考的这篇文章
https://www.jianshu.com/p/1a931d943fb4
private int[] getWindowSizeFirst() {
Rect outRect1 = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(outRect1);
int widthPixel = outRect1.width();
int heightPixel = outRect1.height();
return new int[]{widthPixel,heightPixel};
}
private int[] getWindowSizeSecond() {
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
return new int[]{width,height};
}
private int[] getWindowSizeThird() {
Display defaultDisplay = getWindowManager().getDefaultDisplay();
Point point = new Point();
defaultDisplay.getSize(point);
int x = point.x;
int y = point.y;
return new int[]{x,y};
}
private int[] getWindowSizeFourth() {
DisplayMetrics outMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
int widthPixels = outMetrics.widthPixels;
int heightPixels = outMetrics.heightPixels;
return new int[]{widthPixels,heightPixels};
}
private int[] getWindowSizeFifth() {
Point outSize = new Point();
getWindowManager().getDefaultDisplay().getRealSize(outSize);
int x = outSize.x;
int y = outSize.y;
return new int[]{x,y};
}
private int[] getWindowSizeSixth() {
DisplayMetrics outMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getRealMetrics(outMetrics);
int widthPixel = outMetrics.widthPixels;
int heightPixel = outMetrics.heightPixels;
return new int[]{widthPixel,heightPixel};
}
其中,第五和第六个方法不一样,得到的高度的确为屏幕的显示高度,我的K40显示高度为2400
但是,令人奇怪的是:
在我写的测试方法的demo中
其他的方法结果中高度的值全都是 2276
只有第五,第六种方法是 2400
经过我的大量测试,状态栏的高度值为80(demo和项目代码都是)
int statusBarHeight1 = -1;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
statusBarHeight1 = getResources().getDimensionPixelSize(resourceId);
}
ActionBar(使用默认高度的ToolBar也一样)的高度值为154,获取默认actionbar的高度如下
TypedValue tv =new TypedValue();
if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
height = TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
}
//height自己定义即可
因此,我设置的第一屏的View的高度的理论值为2400-154-80 = 2166
但是,在项目的代码中,第一种方法却给出了2320的结果,也就是恰好减去了状态栏的高度
但除了第五和第六种方法都还是2276,不太清晰的一个数值。
具体原因我也不是很清楚,但是就目前发现的情况可以得出结论,如果读者也跟我一样不知道为什么的话,就可以采取第五和第六种方法,再减去状态栏和toolbar的高度即可,也能得到正确答案。
总而言之,具体方法还是要根据实际情况来,第五和第六种就完全够我们初学者使用了。