0

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},
            )
kkkkk
  • 572
  • 1
  • 10
  • 21

1 Answers1

1

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

william xyz
  • 710
  • 5
  • 19
  • 1
    I've tried it before. But as you are saying onKeyEvent does not trigger on first back pressed. I needed to clear focus as soon as keyboard gone. I've used this https://stackoverflow.com/a/70506309/3797879. Not ideal solution, but it works. – kkkkk Jun 05 '23 at 08:46