英文:
Android Compose TextField and focus on back button click
问题
如何在点击返回按钮时取消对TextField的焦点。键盘已关闭,但TextField仍然具有焦点、光标等。
我看到了这个链接,但我没有收到onFocusEvent,因为它仍然处于焦点状态。
var textFieldValue = remember { mutableStateOf(TextFieldValue("")) }
TextField(
value = textFieldValue.value,
onValueChange = { textFieldValue.value = it },
)
英文:
How to remove focus from a TextField on back button click. Keyboard is gone, but a TextField still has a focus, cursor etc.
I've saw this link, bo I am not getting onFocusEvent, because it still is focused.
var textFieldValue = remember { mutableStateOf(TextFieldValue("")) }
TextField(
value = textFieldValue.value,
onValueChange = { textFieldValue.value = it},
)
答案1
得分: 1
你可以使用 LocalFocusManager
并拦截 onKeyEvent
来实现这一点。不过要注意,虽然代码是正确的,但 onKeyEvent
仅在键盘关闭时触发,所以在这种情况下会表现如下:
- 第一次返回按键:关闭键盘;
- 第二次返回按键:触发
onKeyEvent
并清除焦点;
val focusManager = LocalFocusManager.current
var textFieldValue = remember { mutableStateOf(TextFieldValue("")) }
TextField(
value = textFieldValue.value,
onValueChange = { textFieldValue.value = it},
modifier = Modifier
.onKeyEvent { event ->
if (event.key.nativeKeyCode == android.view.KeyEvent.KEYCODE_BACK) {
focusManager.clearFocus()
true
} else {
false
}
}
)
当键盘打开时无法拦截返回按键的问题有一个未解决的问题:https://issuetracker.google.com/issues/241705563
英文:
You can achieve this be using LocalFocusManager
and intercepting with onKeyEvent
. There's a catch though, while the code is correct, onKeyEvent
is only triggered when keyboard is closed, so in this case it'd behave like:
- first back press: closes keyboard;
- second back press: triggers
onKeyEvent
and clears focus;
val focusManager = LocalFocusManager.current
var textFieldValue = remember { mutableStateOf(TextFieldValue("")) }
TextField(
value = textFieldValue.value,
onValueChange = { textFieldValue.value = it},
modifier = Modifier
.onKeyEvent { event ->
if (event.key.nativeKeyCode == android.view.KeyEvent.KEYCODE_BACK) {
focusManager.clearFocus()
true
} else {
false
}
}
)
There's an open issue for back not being intercepted when keyboard is open: https://issuetracker.google.com/issues/241705563
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论