Search code examples
kotlinandroid-jetpack-composejetbrains-composecompose-multiplatform

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


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?


Solution

  • 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)
           }