自己用的,方便以后找
mBinding.clBottom是底部控件,软键盘弹出时放在软键盘上方,软键盘隐藏时在最底部
mBinding.clBottom.viewTreeObserver.addOnGlobalLayoutListener { // 获取屏幕的高度 val screenHeight: Int = mBinding.clBottom.getRootView().getHeight() // 获取当前布局的可见高度 val rect = Rect() mBinding.clBottom.getWindowVisibleDisplayFrame(rect) // 计算键盘的高度 var keyboardHeight = screenHeight - rect.bottom; if (keyboardHeight > screenHeight * 0.15) { // 键盘显示 showKeyBoardHeight=keyboardHeight mBinding.clBottom.updateLayoutParams<ConstraintLayout.LayoutParams> { bottomMargin = showKeyBoardHeight-hideKeyBoardHeight } } else { hideKeyBoardHeight=keyboardHeight // 键盘隐藏 mBinding.clBottom.updateLayoutParams<ConstraintLayout.LayoutParams> { bottomMargin = 0 } } }
mBinding.clBottom.updateLayoutParams<ConstraintLayout.LayoutParams> {
bottomMargin = showKeyBoardHeight-hideKeyBoardHeight
}
下方android代码即为上方kotlin,主要用于设置空间的bottomMargin
ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) mBinding.clBottom.getLayoutParams();
layoutParams.bottomMargin = showKeyBoardHeight - hideKeyBoardHeight;
mBinding.clBottom.setLayoutParams(layoutParams);
部分手机可能设置了底部虚拟导航栏等,导致获取的屏幕高度需要再减去hideKeyBoardHeight得出来的高度才是正确高度,直接使用showKeyBoardHeight可能导致mBinding.clBottom和软键盘之间有底部虚拟导航栏的高度大小的空隙