Capture and release focus

In specialized interaction modes (such as an embedded drawing canvas, game controller surface, or modal input dialog), your app might need to temporarily lock focus to a single component and prevent Tab or directional keys from navigating away.

Capture focus

To capture focus, invoke captureFocus() on a FocusRequester:

val focusRequester = remember { FocusRequester() }

Box(
    modifier = Modifier
        .focusRequester(focusRequester)
        .focusable()
        .onFocusChanged { focusState ->
            if (focusState.isFocused) {
                focusRequester.captureFocus()
            }
        }
)

While focus is captured, standard focus navigation keys (such as Tab) don't move focus to neighboring components.

Release focus

To exit the captured state and restore normal focus navigation across the UI, call freeFocus():

IconButton(
    onClick = {
        focusRequester.freeFocus()
    }
) {
    Icon(Icons.Default.Close, contentDescription = "Exit focus lock")
}