Android获取软键盘高度
2023-04-25 本文已影响0人
_发强
private var keyboardHeight = 0
private fun observeKeyboardHeight() {
val rootView: View = window.decorView.findViewById(android.R.id.content)
rootView.viewTreeObserver.addOnGlobalLayoutListener(object :
ViewTreeObserver.OnGlobalLayoutListener {
private var isKeyboardVisible = false
override fun onGlobalLayout() {
val rect = Rect()
rootView.getWindowVisibleDisplayFrame(rect)
val screenHeight = rootView.rootView.height
keyboardHeight = screenHeight - rect.bottom
if (keyboardHeight > 150 && !isKeyboardVisible) {
isKeyboardVisible = true;
// 键盘弹出
Log.i("show....$keyboardHeight")
showedKeyboard(true)
} else if (keyboardHeight <= 150 && isKeyboardVisible) {
isKeyboardVisible = false;
// 键盘隐藏
Log.i("hide....$keyboardHeight")
showedKeyboard(false)
}
}
})
}
某些设备需要同步配合获取底部导航栏高度:
private fun getNavigationBarHeight(context: Context): Int {
try {
val resourceId =
context.resources.getIdentifier("navigation_bar_height", "dimen", "android")
return if (resourceId > 0) {
context.resources.getDimensionPixelSize(resourceId)
} else {
0
}
} catch (e: Exception) {
return 0
}
}