通过键盘弹出将View平滑移动到键盘上方

532 阅读1分钟

假如是这么一个场景 图画的有点好看,在我们Activity没有设置android:windowSoftInputMode="adjustResize" 的时候是有可能将整个背景顶到屏幕外的,如果我们不想让键盘弹出的时候将当前布局顶出屏幕 是需要设置一些flag的 这里我们先不深究原理 ,感兴趣的可以找一些相关博客。 当设置后,布局就不会顶起,但是相对的来说,我们有一个功能是将提交按钮在键盘弹起的时候一直显示在键盘的最上方,以下为我个人的理解和记录 WeChat23a50e9b26c339efc18c71b90be39f97.png

WeChatd801057e95dc689db4c2e0857c54778f.png

  1. 首先分两种情况 一种是一进入页面的键盘弹出,一种是当点击按钮的时候键盘弹出,这里我们处理的逻辑是一样的,通过监听键盘的高度来区分是弹出还是关闭
KeyboardUtils.registerSoftInputChangedListener(activity?.window!!) { height ->
    if (height > 0) {
        onSoftKeyboardOpened(height)
    } else {
        onSoftKeyboardClosed()
    }
}

来做一些属性动画

//关闭
private fun onSoftKeyboardClosed() {
    val mAnimatorTranslateY = ObjectAnimator.ofFloat(btn_sumbit, "translationY", btn_sumbit.translationY, 0f)
    mAnimatorTranslateY.duration = 300
    mAnimatorTranslateY.interpolator = AccelerateDecelerateInterpolator()
    mAnimatorTranslateY.start()
}
//弹出上移动
private fun onSoftKeyboardOpened(height: Int) {
    val location = IntArray(2)
    btn_sumbit?.getLocationOnScreen(location) //获取body在屏幕中的坐标,控件左上角
    val y = location[1]
    val bottom: Int = ScreenUtils.getAppScreenHeight() - (y + btn_sumbit.height)
    if (height < bottom) return
    val mAnimatorTranslateY = ObjectAnimator.ofFloat(btn_sumbit, "translationY", 0.0f, -(height - bottom).toFloat())
    mAnimatorTranslateY.duration = 300
    mAnimatorTranslateY.interpolator = AccelerateDecelerateInterpolator()
    mAnimatorTranslateY.start()
}
override fun onDestroy() {
    super.onDestroy()
    //记得要reset
    KeyboardUtils.unregisterSoftInputChangedListener(activity?.window!!)
}