问题描述
限时送ChatGPT账号..我使用的是 BasicTextField.
I'm using BasicTextField.
当我开始编辑时,后退按钮变成隐藏键盘按钮(向下箭头).
When I start editing, back button becomes hide keyboard button(arrow down).
第一次按下后退按钮会隐藏键盘,但焦点仍在文本字段上.onFocusChanged
和 BackPressHandler
处理程序都没有被调用.
First press on back button hides keyboard, but the focus is still on the text field. Both onFocusChanged
and BackPressHandler
handlers not getting called.
第二次按下后退按钮清除焦点:onFocusChanged
被调用而 BackPressHandler
不是.
Second press on back button clears focus: onFocusChanged
is called and BackPressHandler
is not.
BackHandler {
println("BackPressHandler")
}
val valueState = remember { mutableStateOf(TextFieldValue(text = "")) }
BasicTextField(
value = valueState.value,
onValueChange = {
valueState.value = it
},
modifier = Modifier
.fillMaxWidth()
.onFocusChanged {
println("isFocused ${it.isFocused}")
}
)
第三次 BackHandler 工作正常.只是用于测试,我不应该在这里需要它,它预计在第一次点击后退按钮后焦点会丢失
Third time BackHandler works fine. Just used it for testing, I shouldn't be needed it here, it expected focus to get lost after first back button tap
推荐答案
撰写问题 带有焦点文本字段可防止后退按钮在键盘隐藏时关闭应用程序.它被标记为已修复,但将包含在未来的某个版本中,而不是 1.0
There's a compose issue with focused text field prevents back button from dismissing the app when keyboard is hidden. It's marked as fixed, but will be included in some future release, not in 1.0
但是,据我了解,在键盘被解除后文本字段没有失去焦点的事实是 Android 上的预期行为(因为可能连接了键盘?我没有得到原因).这也是它在旧的 android 布局中的工作方式
But, as I understand, the fact that text field is not loosing focus after keyboard being dismissed, is intended behaviour on Android(because of possible connected keyboard? I didn't get the reason). And this is how it works in old android layout too
这对我来说似乎很奇怪,所以我提供了以下修饰符,它在键盘消失时退出焦点:
It seems strange to me, so I came with the following modifier which resigns focus when keyboard disappears:
fun Modifier.clearFocusOnKeyboardDismiss(): Modifier = composed {
var isFocused by remember { mutableStateOf(false) }
var keyboardAppearedSinceLastFocused by remember { mutableStateOf(false) }
if (isFocused) {
val imeIsVisible = LocalWindowInsets.current.ime.isVisible
val focusManager = LocalFocusManager.current
LaunchedEffect(imeIsVisible) {
if (imeIsVisible) {
keyboardAppearedSinceLastFocused = true
} else if (keyboardAppearedSinceLastFocused) {
focusManager.clearFocus()
}
}
}
onFocusEvent {
if (isFocused != it.isFocused) {
isFocused = it.isFocused
if (isFocused) {
keyboardAppearedSinceLastFocused = false
}
}
}
}
附言您需要为 LocalWindowInsets.current.ime
p.s. You need to install accompanist insets dependency for LocalWindowInsets.current.ime
用法:
BasicTextField(
value = valueState.value,
onValueChange = {
valueState.value = it
},
modifier = Modifier
.clearFocusOnKeyboardDismiss()
)
这篇关于如何在关闭键盘时清除 TextField 焦点并防止在 Jetpack Compose 中退出应用程序所需的两次后退?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论