If keyboard is opened the next code returns true (for showingKeyboard) on Android 11 (30 API) or false otherwise:

private fun registerGlobalLayoutListener() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        window.decorView.viewTreeObserver.addOnGlobalLayoutListener(globalLayoutListener)
    }
}

private fun unregisterGlobalLayoutListener() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        window.decorView.viewTreeObserver.removeOnGlobalLayoutListener(globalLayoutListener)
    }
}

@RequiresApi(Build.VERSION_CODES.M)
private val globalLayoutListener = ViewTreeObserver.OnGlobalLayoutListener {
    val showingKeyboard =
        WindowInsetsCompat.toWindowInsetsCompat(window.decorView.rootWindowInsets)
            .isVisible(WindowInsetsCompat.Type.ime())
    viewModel.setKeyboardShowing(showingKeyboard)
}

On Android 6-10 (23-29) it returns true even if keyboard is not opened (not visible)

1

There are 1 best solutions below

0
On

Try adding android:windowSoftInputMode="adjustResize" to your activity in the AndroidManifest.xml file.

Also check this answer for more details: https://stackoverflow.com/a/66805360/949280