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

前端 未结 30 1887
情书的邮戳
情书的邮戳 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:32

    With the new feature WindowInsetsCompat in androidx core release 1.5.0-alpha02 you could check the visibility of the soft keyboard easily as below

    Quoting from reddit comment

    val View.keyboardIsVisible: Boolean
        get() = WindowInsetsCompat
            .toWindowInsetsCompat(rootWindowInsets)
            .isVisible(WindowInsetsCompat.Type.ime())
    

    Some note about backward compatibility, quoting from release notes

    New Features

    The WindowInsetsCompat APIs have been updated to those in the platform in Android 11. This includes the new ime() inset type, which allows checking the visibility and size of the on-screen keyboard.

    Some caveats about the ime() type, it works very reliably on API 23+ when your Activity is using the adjustResize window soft input mode. If you’re instead using the adjustPan mode, it should work reliably back to API 14.

    References

    • Twitter WindowInsetsCompat announcement
    • Reddit thread
    • Androidx Core 1.5.0-alpha02 release notes
    • WindowInsetsCompat Docs

提交回复
热议问题