运行效果图
项目中一般会有“评论”的功能,为了更好的进行UI交互操作,就需要监听键盘弹出并获取键盘高度。所以就写一个键盘工具类。
监听键盘弹出思路:
首先获取DecorView.height - Rect.bottom(屏幕可视区域)的值设为kHeight(预定键盘高度)
为了让kHeight更具准确性,需要提供一个阈值设为minKHeight
所以键盘高度就为kHeight>minKHeight?0:kHeight
kHeight>0,键盘弹出;kHeight=0,键盘没有弹出
实现代码:
// 最小键盘高度的阈值
final int MIN_KEYBOARD_HEIGHT_PX = 200;
// 屏幕可见区域
private final Rect windowVisibleDisplayFrame = new Rect();
// 保存最后可视区域高度
private int lastKeyboardHeight;
private ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// 获取屏幕可视区域
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(windowVisibleDisplayFrame);
// 获取键盘高度
int currentKeyboardHeight = activity.getWindow().getDecorView().getHeight() - windowVisibleDisplayFrame.bottom;
if (lastKeyboardHeight != currentKeyboardHeight) {
if (currentKeyboardHeight > MIN_KEYBOARD_HEIGHT_PX) {// 键盘可见时回调
if (onKeyboardListener != null) {
onKeyboardListener.onKeyboardShown(currentKeyboardHeight);
}
} else {// 键盘隐藏时回调
if (onKeyboardListener != null) {
onKeyboardListener.onKeyboardHidden();
}
}
lastKeyboardHeight = currentKeyboardHeight;
}
}
};
参考:https://pspdfkit.com/blog/2016/keyboard-handling-on-android/