获取屏幕尺寸
- 不包含底部虚拟按键
WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics displayMetrics = new DisplayMetrics();
windowManager.getDefaultDisplay().getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
- 包含底部虚拟按键
int height = getWindow().getDecorView().getHeight();
- 获取应用显示区域
Rect rect = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
rect.top
status_bar_height,即状态栏高度.
(rect.bottom - rect.top)
应用显示区域.
监听键盘状态
原理:
1.获取应用显示区域(不包含虚拟按键).
2.获取屏幕高度(不包含虚拟按键).
3.比较两者大小(正常差值为status_bar高度)
注:这种方法前提是软键盘会影响界面布局,所以需要在AndroidManifest里给activity添加android:windowSoftInputMode="adjustResize"
代码实现:
mActivityMainRootView.getViewTreeObserver().addOnGlobalLayoutListener(mOnGlobalLayoutListener);
private ViewTreeObserver.OnGlobalLayoutListener mOnGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect rect = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics displayMetrics = new DisplayMetrics();
windowManager.getDefaultDisplay().getMetrics(displayMetrics);
int screenHeight =displayMetrics.heightPixels;
int heightDiff = screenHeight - (rect.bottom - rect.top);
if (keyboardHeight == 0 && heightDiff > statusBarHeight) {
keyboardHeight = heightDiff - statusBarHeight;
}
if (isShowKeyboard) {
if (heightDiff <= statusBarHeight) {
isShowKeyboard = false;
}
} else {
if (heightDiff > statusBarHeight) {
isShowKeyboard = true;
}
}
}
};
参考链接:http://cashow.github.io/android-get-keyboard-height.html