键盘唤出时对应控件上滑

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后也会触发 所用增加一个判断在返回桌面时是否有使用键盘

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值