Android 监听软键盘SoftKeyboard的高度变化

在这里插入图片描述

方案一,使用blankj:utilcode

        KeyboardUtil.observeKeyboard(requireActivity()) {
            val param = binding.flKeyboard.layoutParams
            param.height = it
            binding.flKeyboard.layoutParams = param
        }

方案二,自定义KeyboardUtil监听

  • KeyboardUtil
package com.vision.mykeyboard

import android.app.Activity
import android.graphics.Rect

class KeyboardUtil {

    companion object {
        fun observeKeyboard(
            activity: Activity,
            listener: (keyboardHeight: Int) -> Unit
        ) {
            var lastKeyboardHeight = -1
            val decorView = activity.window.decorView
            //监听view的变化
            decorView.viewTreeObserver.addOnGlobalLayoutListener {
                val rect = Rect()
                decorView.getWindowVisibleDisplayFrame(rect)
                //屏幕上未被键盘挡住的区域高度
                val displayHeight = rect.height()
                //导航栏的高度
                val barHeight = getNavBarHeight(activity) + getStatusBarHeight(activity)
                //键盘高度
                val keyboardHeight = decorView.height - displayHeight - barHeight
                if (lastKeyboardHeight != keyboardHeight) {
                    listener.invoke(keyboardHeight)
                }
                lastKeyboardHeight = keyboardHeight
            }
        }

        //获取底部导航栏的高度
        private fun getNavBarHeight(activity: Activity): Int {
            val res = activity.resources
            val resourceId = res.getIdentifier("navigation_bar_height", "dimen", "android")
            return if (resourceId != 0) {
                res.getDimensionPixelSize(resourceId)
            } else {
                0
            }
        }

        //获取顶部状态栏高度
        private fun getStatusBarHeight(activity: Activity): Int {
            val resources = activity.resources
            val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android")
            return resources.getDimensionPixelSize(resourceId)
        }
    }

}
  • 使用
    flKeyboard是一个占位的FrameLayout
        KeyboardUtil.observeKeyboard(requireActivity()) {
            val param = binding.flKeyboard.layoutParams
            param.height = it
            binding.flKeyboard.layoutParams = param
        }

Demo下载地址

https://gitee.com/olleh/keyboard-util

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值