如果打开键盘,则下一个代码在 Android 11 (30 API) 上返回true
(for showingKeyboard
) 或false
其他:
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)
}
在 Android 6-10 (23-29) 上,true
即使未打开键盘(不可见)也会返回