如何在Jetpack Compose中检测键盘的打开和关闭? [英] How can I detect keyboard opening and closing in jetpack compose?
本文介绍了如何在Jetpack Compose中检测键盘的打开和关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Compose中找到的唯一方法是使用accompanist-insets
,这会删除窗口嵌入。这会导致我的应用程序布局出现其他问题。
Android的方式似乎是this,我可以将其传递到我的Compose应用程序中并相应地执行操作。
喷气背包制作有其他方法吗?
推荐答案
我找到了使用安卓viewTreeObserver
的方法。它本质上是Android版本,但它调用了可以在Compose中使用的回调。
class MainActivity : ComponentActivity() {
var kbGone = false
var kbOpened: () -> Unit = {}
var kbClosed: () -> Unit = {}
override fun onCreate(state: Bundle?) {
super.onCreate(state)
setContent {
kbClosed = {
// dismiss the keyboard with LocalFocusManager for example
}
kbOpened = {
// something
}
MyComponent()
}
setupKeyboardDetection(findViewById<View>(android.R.id.content))
}
fun setupKeyboardDetection(contentView: View) {
contentView.viewTreeObserver.addOnGlobalLayoutListener {
val r = Rect()
contentView.getWindowVisibleDisplayFrame(r)
val screenHeight = contentView.rootView.height
val keypadHeight = screenHeight - r.bottom
if (keypadHeight > screenHeight * 0.15) { // 0.15 ratio is perhaps enough to determine keypad height.
kbGone = false
kbOpened()
} else(!kbGone) {
kbGone = true
kbClosed()
}
}
}
}
这篇关于如何在Jetpack Compose中检测键盘的打开和关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文