在键盘出现并在 Android 上应用 adjustPan 后获取视图边界

Get view bounds after keyboard appears and adjustPan applied on Android

我正在使用一种解决方法来检测单击是否在 EditText 之外以执行某些逻辑。当用户点击 EditText 时,键盘出现。 windowSoftInputMode 设置为 adjustPan。所以问题是我看到在页面上推送内容后没有重新计算视图边界。它仍在使用关闭的键盘返回先前的界限。

这是我使用的代码

override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
    currentFocus?.let {
        tryCloseKeyboardAndClearFocusFromEditText(currentFocus as View, ev)
    }
    return super.dispatchTouchEvent(ev)
}

private fun tryCloseKeyboardAndClearFocusFromEditText(focus: View, ev: MotionEvent?) {
    if (focus is TextInputEditText) {
        val outRect = Rect()
        (focus as? TextInputEditText)?.getGlobalVisibleRect(outRect)
        if (!outRect.contains(ev?.rawX?.toInt() ?: 0, ev?.rawY?.toInt() ?: 0)) {
            closeKeyboard()
            (focus as? TextInputEditText)?.clearFocus()
        }
    }
}

所以 getGlobalVisibleRec 总是 returns 相同的值,无论键盘是打开还是关闭,屏幕上的内容实际上是向上推的。例如,MotionEvent 坐标是 100、400,而 EditText 显示的是 60、490,例如事件,尽管我直接点击它。

有没有办法在键盘关闭或打开时获得屏幕上关于偏移量的实际视图?

找到了一个解决方案,所以我现在使用 getLocationInWindow 并添加 heightwidth 来计算边界。按预期工作。 如果有人能解释为什么 getGlobalVisibleRectgetLocalVisibleRect 不起作用,请解释一下。

private fun tryCloseKeyboardAndClearFocusFromEditText(focus: View, ev: MotionEvent?) {
        if (focus is TextInputEditText) {
            val location = IntArray(2)
            (focus as? TextInputEditText)?.let{
                it.getLocationInWindow(location)
                val outRect = Rect(location[0], location[1], location[0] + it.width, location[1] + it.height)
                if (!outRect.contains(ev?.rawX?.toInt() ?: 0, ev?.rawY?.toInt() ?: 0)) {
                    closeKeyboard()
                    it.clearFocus()
                }
            }
        }
    }