Android Compose TextField 和在点击返回按钮时聚焦。

huangapple go评论68阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年6月5日 01:20:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76401578.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定