一、不包含虚拟键盘
1、通过 getResources 获取
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
int width1 = displayMetrics.widthPixels;
2、通过 WindowManager 获取,不包括虚拟按键
DisplayMetrics dm = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getRealMetrics(dm);
int width2 = dm.widthPixels;
3、获取屏幕的默认分辨率,不包括虚拟按键
Display display = this.getWindowManager().getDefaultDisplay();
int width3 = display.getWidth();
二、包含虚拟键盘
private int getHasVirtualKey() {
int dpi = 0;
Display display = getWindowManager().getDefaultDisplay();
DisplayMetrics dm = new DisplayMetrics();
@SuppressWarnings("rawtypes")
Class c;
try {
c = Class.forName("android.view.Display");
@SuppressWarnings("unchecked")
Method method = c.getMethod("getRealMetrics", DisplayMetrics.class);
method.invoke(display, dm);
dpi = dm.heightPixels;
} catch (Exception e) {
e.printStackTrace();
}
return dpi;
}