How do I detect if software keyboard is visible on Android Device or not?

前端 未结 30 1886
情书的邮戳
情书的邮戳 2020-11-22 10:59

Is there a way in Android to detect if the software (a.k.a. \"soft\") keyboard is visible on screen?

30条回答
  •  一个人的身影
    2020-11-22 11:55

    I converted the answer to the kotlin, hope this helps for kotlin users.

    private fun checkKeyboardVisibility() {
        var isKeyboardShowing = false
    
        binding.coordinator.viewTreeObserver.addOnGlobalLayoutListener {
            val r = Rect()
            binding.coordinator.getWindowVisibleDisplayFrame(r)
            val screenHeight = binding.coordinator.rootView.height
    
            // r.bottom is the position above soft keypad or device button.
            // if keypad is shown, the r.bottom is smaller than that before.
            val keypadHeight = screenHeight - r.bottom
    
    
            if (keypadHeight > screenHeight * 0.15) { // 0.15 ratio is perhaps enough to determine keypad height.
                // keyboard is opened
                if (!isKeyboardShowing) {
                    isKeyboardShowing = true
    
                }
            } else {
                // keyboard is closed
                if (isKeyboardShowing) {
                    isKeyboardShowing = false
    
                }
            }
        }
    }
    

提交回复
热议问题