获取屏幕、状态栏、标题栏高度
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
//屏幕宽高--包含状态栏。注意,华为的手机不包含下面的【HOME键那一栏】,如1920屏幕只有1794
Point point = new Point();
Display disp = this.getWindowManager().getDefaultDisplay();
disp.getSize(point);
//除去状态栏后的高度。从这两个数据可以算出1920*1080手机状态栏高度为75,即【25*3】,这个值一般是固定的!
Rect rect = new Rect();
this.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
//除去状态栏和标题栏的高度,这个值默认也状态栏的一样,即也是75
Rect rect2 = new Rect();
this.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getDrawingRect(rect2);
Log.i("bqt", point.y + "---" + rect.height() + "---" + rect2.height());//【奇酷1920-1848-1776】【华为1794-1719-1644】
}
}
获取屏幕宽高等信息方法总结
方法1,废弃了
int screenWidth = getWindowManager().getDefaultDisplay().getWidth();
int screenHeight = getWindowManager().getDefaultDisplay().getHeight();
Log.e("bqt", "screenWidth=" + screenWidth + "; screenHeight=" + screenHeight); //screenWidth=1080或720; screenHeight=1920或1280
方法2,API13(3.2)之后才能用
Point outSize = new Point();
getWindowManager().getDefaultDisplay().getSize(outSize);
int screenWidth = outSize.x;
int screenHeight = outSize.y;
Log.e("bqt", "screenWidth=" + screenWidth + "; screenHeight=" + screenHeight); //screenWidth=1080或720; screenHeight=1920或1280
方法3,可以兼容低版本
DisplayMetrics dm = getResources().getDisplayMetrics();
int screenWidth = dm.widthPixels; // 屏幕宽px
int screenHeight = dm.heightPixels; // 屏幕高px
Log.e("bqt", "screenWidth=" + screenWidth + "; screenHeight=" + screenHeight); //screenWidth=1080; screenHeight=1920
float density = dm.density; // 像素比例:0.75/1.0/1.5/2.0
int densityDPI = dm.densityDpi; // 每寸像素:120/160/240/320
Log.e("bqt" + " DisplayMetrics", "density=" + density + "; densityDPI=" + densityDPI); // density=3.0或2.0; densityDPI=480或320
float xdpi = dm.xdpi;
float ydpi = dm.ydpi;
Log.e("bqt" + " DisplayMetrics", "xdpi=" + xdpi + "; ydpi=" + ydpi); //xdpi=160.42105; ydpi=159.89508;