How to check visibility of software keyboard in Android?

前端 未结 30 4419
半阙折子戏
半阙折子戏 2020-11-21 04:43

I need to do a very simple thing - find out if the software keyboard is shown. Is this possible in Android?

30条回答
  •  不知归路
    2020-11-21 05:29

    There's a hidden method can help for this, InputMethodManager.getInputMethodWindowVisibleHeight. But I don't know why it's hidden.

    import android.content.Context
    import android.os.Handler
    import android.view.inputmethod.InputMethodManager
    
    class SoftKeyboardStateWatcher(private val ctx: Context) {
      companion object {
        private const val DELAY = 10L
      }
    
      private val handler = Handler()
      private var isSoftKeyboardOpened: Boolean = false
    
      private val height: Int
        get() {
          val imm = ctx.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
          val method = imm.javaClass.getMethod("getInputMethodWindowVisibleHeight")
          method.isAccessible = true
          return method.invoke(imm) as Int
        }
    
      private val task: Runnable by lazy {
        Runnable {
          start()
          if (!isSoftKeyboardOpened && height > 0) {
            isSoftKeyboardOpened = true
            notifyOnSoftKeyboardOpened(height)
          } else if (isSoftKeyboardOpened && height == 0) {
            isSoftKeyboardOpened = false
            notifyOnSoftKeyboardClosed()
          }
        }
      }
    
      var listener: SoftKeyboardStateListener? = null
    
      interface SoftKeyboardStateListener {
        fun onSoftKeyboardOpened(keyboardHeightInPx: Int)
        fun onSoftKeyboardClosed()
      }
    
      fun start() {
        handler.postDelayed(task, DELAY)
      }
    
      fun stop() {
        handler.postDelayed({
          if (!isSoftKeyboardOpened) handler.removeCallbacks(task)
        }, DELAY * 10)
      }
    
      private fun notifyOnSoftKeyboardOpened(keyboardHeightInPx: Int) {
        listener?.onSoftKeyboardOpened(keyboardHeightInPx)
      }
    
      private fun notifyOnSoftKeyboardClosed() {
        listener?.onSoftKeyboardClosed()
      }
    }
    

提交回复
热议问题