简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM