var isKeyBordShowing: Boolean = false
private fun setListenerToRootView() {
val rootView: View = ((context)as Activity).window.decorView.findViewById(android.R.id.content)
rootView.viewTreeObserver.addOnGlobalLayoutListener {
val mKeyboardUp = isKeyboardShown(rootView)
val rect = Rect()
rootView.getWindowVisibleDisplayFrame(rect)
val screenHeight = rootView.rootView.height
val keyboardHeight = screenHeight - rect.bottom
if (mKeyboardUp) {
isKeyBordShowing = true
startAnimationOnShowKeyBoard(keyboardHeight)
} else {
if (isKeyBordShowing){
isKeyBordShowing = false
startAnimationOnHideKeyBoard(keyboardHeight)
}
}
//如果只想检测一次,需要注销
//rootView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
}
private fun isKeyboardShown(rootView: View): Boolean {
val softKeyboardHeight = 10
val r = Rect()
rootView.getWindowVisibleDisplayFrame(r)
val dm: DisplayMetrics = rootView.resources.displayMetrics
val heightDiff: Int = rootView.bottom - r.bottom
return heightDiff > softKeyboardHeight * dm.density
}
private fun startAnimationOnShowKeyBoard(animationY: Int) {
rlContentY = rlContent!!.y
val animator = ValueAnimator.ofFloat(0f, 1f)
animator.duration = 300
animator.addUpdateListener { animation ->
val curValue = animation.animatedValue as Float
rlContent!!.y = rlContentY - curValue * animationY
}
animator.start()
}
private fun startAnimationOnHideKeyBoard(animationY: Int) {
val animator = ValueAnimator.ofFloat(0f, 1f)
animator.duration = 10
animator.addUpdateListener {animation->
val curValue = animation.animatedValue as Float
rlContent!!.y = rlContentY - curValue * animationY
}
animator.start()
}
对应的父容器需要设置该属性android:isScrollContainer="true"
不然在键盘弹出时 系统会控制布局做改变 但是控件的坐标不会改变
这个监听在回桌面在回到app后也会触发 所用增加一个判断在返回桌面时是否有使用键盘