Android 获取键盘高度,显示键盘和隐藏键盘

运行效果图

   

项目中一般会有“评论”的功能,为了更好的进行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;
            }
        }
    };

Demo下载 

参考:https://pspdfkit.com/blog/2016/keyboard-handling-on-android/

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值