方案一,使用blankj:utilcode
KeyboardUtil.observeKeyboard(requireActivity()) {
val param = binding.flKeyboard.layoutParams
param.height = it
binding.flKeyboard.layoutParams = param
}
方案二,自定义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
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