How to react to the Enter key being pressed while ...
# compose-desktop
v
How to react to the Enter key being pressed while editing in TextField? (with singleLine == true)
i
You can use `Modifier.onPreviewKeyEvent`:
Copy code
import androidx.compose.desktop.Window
import androidx.compose.material.TextField
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.key.type

@OptIn(ExperimentalComposeUiApi::class)
fun main() = Window {
    TextField("", {}, modifier = Modifier.onPreviewKeyEvent {
        if (it.key == Key.Enter && it.type == KeyEventType.KeyDown) {
            println("Enter")
            true
        } else {
            false
        }
    })
}
P.S. probably with
singleLine == true
we should propagate Enter key to the parent nodes, so
onKeyEvent
would work too 🤔
🙌 2
v
Thank you!
a
it appears to be a deprecated solution, which even shows an error instead of a warning:
Copy code
e: ...kt This API is experimental and is likely to change in the future.
i
deprecated solution
only
Window
is deprecated here (we can use
singleWindowApplication
instead), the rest of the code stays the same.
This API is experimental and is likely to change in the future.
Just add
@OptIn(ExperimentalComposeUiApi::class)
to your function
a
Thanks
t
@Igor Demin Why does KeyboardActions not get called for the enter key?