How to clear focus of BasicTextField upon clicking somewhere else in Compose Multiplatform?
Asked Answered
V

1

10

I have a BasicTextField in Jetbrains Compose Multiplatform for desktop. When I click on it, the TextField gets focus and becomes editable. However, when I click somewhere else in my application, the focus is not lost and the field is still editable as if I just clicked on it.

I know this behavior is normal and intended. Nonetheless, I want to the TextField to become unfocused when the user clicks somewhere else, regardless of it being a clickable or non-clickable composable.

How do I achieve this?

Vagary answered 20/12, 2021 at 8:36 Comment(0)
C
15

This is one way I've done it in the past.

 val keyboardController = LocalSoftwareKeyboardController.current
 val focusManager = LocalFocusManager.current
 val interactionSource = remember { MutableInteractionSource() }

Then I made my parent layout clickable.

Box(modifier = Modifier
       .clickable(
           interactionSource = interactionSource,
           indication = null    // this gets rid of the ripple effect
       ) {
           keyboardController?.hide()
           focusManager.clearFocus(true)
       }
Crookes answered 20/12, 2021 at 9:45 Comment(2)
Thanks! Still does not clear focus when another clickable is clicked, but it works well enough for me :)Vagary
I added the Modifier from the answer to my Column and found the same problem that any clickable in the Column needs to also call focusManager.clearFocus(true). Without adding anything, the keyboard has been getting hidden perfectly, so I didn't add that part of the answer.Cot

© 2022 - 2024 — McMap. All rights reserved.