欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  科技

彻底解决软键盘遮挡DialogFragment

程序员文章站 2022-07-05 09:34:22
问题描述点击edittext,弹出软键盘,dialog略微上移,edittext和下面的按钮还是被遮挡,上移的部分被切割解决方案设置dialog的inputMode,取消软键盘弹出自动上移监听软键盘弹出事件,动态设置dialog的paddingBottomoverride fun init() { dialog?.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING)...
问题描述

点击edittext,弹出软键盘,dialog略微上移,edittext和下面的按钮还是被遮挡,上移的部分被切割

解决方案

设置dialog的inputMode,取消软键盘弹出自动上移
监听软键盘弹出事件,动态设置dialog的paddingBottom

override fun init() {
        dialog?.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING)
        globalListener = KeyboardUtils.registerSoftInputChangedListener(activity, object : KeyboardUtils.OnSoftInputChangedListener {
            override fun onSoftInputChanged(height: Int) {
                dialog?.window?.apply {
                    if (height > 10) {
                        decorView.setPadding(0, 0, 0, 400)
                    } else {
                        decorView.setPadding(0, 0, 0, 0)
                    }
                    attributes = attributes
                }
            }
        })
    }

override fun onDestroy() {
        super.onDestroy()
        if (globalListener != null) {
            KeyboardUtils.unregisterSoftInputChangedListener(activity, globalListener!!)
        }
    }

fun registerSoftInputChangedListener(activity: Activity,
                                         listener: OnSoftInputChangedListener?)
            : ViewTreeObserver.OnGlobalLayoutListener {
        val contentView = activity.findViewById<View>(android.R.id.content)
        sContentViewInvisibleHeightPre = getContentViewInvisibleHeight(activity)
        val globalListener = ViewTreeObserver.OnGlobalLayoutListener {
            if (listener != null) {
                val height = getContentViewInvisibleHeight(activity)
                if (sContentViewInvisibleHeightPre != height) {
                    listener.onSoftInputChanged(height)
                    sContentViewInvisibleHeightPre = height
                }
            }
        }
        contentView.viewTreeObserver.addOnGlobalLayoutListener(globalListener)
        return globalListener
    }

    fun unregisterSoftInputChangedListener(activity: Activity,
                                           listener: ViewTreeObserver.OnGlobalLayoutListener) {
        val contentView = activity.findViewById<View>(android.R.id.content)
        contentView.viewTreeObserver.removeOnGlobalLayoutListener(listener)
    }

private fun getContentViewInvisibleHeight(activity: Activity): Int {
        val contentView = activity.findViewById<View>(android.R.id.content)
        val outRect = Rect()
        contentView.getWindowVisibleDisplayFrame(outRect)
        return contentView.bottom - outRect.bottom
    }
总结

dialog销毁一定要移除global监听,否则回调里面拿到的window是上一次的

本文地址:https://blog.csdn.net/weixin_37165769/article/details/110235489

相关标签: problem