我正在尝试主动观察软键盘的可见性,目前,我正在使用以下方式观察:
WindowInsets.isImeVisible
但是我似乎无法观察到它的状态变化。有人提到使用
ViewCompat.setOnApplyWindowInsetsListener()
但我还不太明白如何实现它来观察键盘的可见性。
我已经成功使用了
WindowInsets.isImeVisible
然而,它只适用于我导航到页面和键盘自动打开的时候。
我正在尝试主动观察软键盘的可见性,目前,我正在使用以下方式观察:
WindowInsets.isImeVisible
但是我似乎无法观察到它的状态变化。有人提到使用
ViewCompat.setOnApplyWindowInsetsListener()
但我还不太明白如何实现它来观察键盘的可见性。
我已经成功使用了
WindowInsets.isImeVisible
以下内容翻译自 S.O 帖子:
您可以使用以下代码来检测键盘是否已经打开或关闭
internal enum class Keyboard {
Opened, Closed
}
@Composable
internal fun keyboardAsState(): State<Keyboard> {
val keyboardState = remember { mutableStateOf(Keyboard.Closed) }
val view = LocalView.current
DisposableEffect(view) {
val onGlobalListener = ViewTreeObserver.OnGlobalLayoutListener {
val rect = Rect()
view.getWindowVisibleDisplayFrame(rect)
val screenHeight = view.rootView.height
val keypadHeight = screenHeight - rect.bottom
keyboardState.value = if (keypadHeight > screenHeight * 0.15) {
Keyboard.Opened
} else {
Keyboard.Closed
}
}
view.viewTreeObserver.addOnGlobalLayoutListener(onGlobalListener)
onDispose {
view.viewTreeObserver.removeOnGlobalLayoutListener(onGlobalListener)
}
}
return keyboardState
}
@Composable
fun KeyboardCheck() {
val keyboard by keyboardAsState()
Log.e("KeyboardCheck", "$keyboard")
TextField(value = "", onValueChange = {})
}
E/KeyboardCheck: Closed
E/KeyboardCheck: Opened
E/KeyboardCheck: Closed
E/KeyboardCheck: Opened
E/KeyboardCheck: Closed