KeyEvent

Class

Common
value class KeyEvent(val nativeKeyEvent: NativeKeyEvent)

When a user presses a key on a hardware keyboard, a KeyEvent is sent to the item that is currently focused. Any parent composable can intercept this key event on its way to the focused item by using Modifier.onPreviewKeyEvent()```onPreviewKeyEvent. If the item is not consumed, it returns back to each parent and can be intercepted by using Modifier.onKeyEvent()```onKeyEvent.

Code Examples

KeyEventSample

@Suppress("UNUSED_ANONYMOUS_PARAMETER")
@Composable
fun KeyEventSample() {
    // When the inner Box is focused, and the user presses a key, the key goes down the hierarchy
    // and then back up to the parent. At any stage you can stop the propagation by returning
    // true to indicate that you consumed the event.
    Box(Modifier.onPreviewKeyEvent { keyEvent1 -> false }.onKeyEvent { keyEvent4 -> false }) {
        Box(
            Modifier.onPreviewKeyEvent { keyEvent2 -> false }
                .onKeyEvent { keyEvent3 -> false }
                .focusable()
        )
    }
}