Box doesn't capture key events in Compose Desktop
Asked Answered
C

1

3

Keys are printed when the TextField is focused but not when the Box itself if focused.

Box(
    modifier = Modifier.onKeyEvent {
        println(it.key)
        false
    }.fillMaxSize().focusable()
) {
    val fieldValue = remember { mutableStateOf(TextFieldValue("")) }
    TextField(
        value = fieldValue.value,
        onValueChange = { fieldValue.value = it }
    )
}
Cochin answered 7/8, 2021 at 16:44 Comment(1)
check out my answer on similar questionPurgatorial
C
2

Inspired by this answer, I change the code.

When you click on the Box, you remove the focus from the TextField but you don't give it to the Box. This has to be done manually.

val focusRequester = FocusRequester()

Box(
    modifier = Modifier.onKeyEvent {
        println(it.key)
        false
    }.fillMaxSize()
        .focusRequester(focusRequester)
        .focusable()
        .clickable (
            interactionSource = remember { MutableInteractionSource() },
            indication = null // To disable the ripple effect
        ) {
            focusRequester.requestFocus()
        }
) {
    val fieldValue = remember { mutableStateOf(TextFieldValue("")) }
    TextField(
        value = fieldValue.value,
        onValueChange = { fieldValue.value = it }
    )
}
Cochin answered 22/8, 2021 at 18:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.