captureFocus

Function

Common
fun FocusRequesterModifierNode.captureFocus(): Boolean

Deny requests to clear focus.

Use this function to send a request to capture focus. If a component captures focus, it will send a FocusState object to its associated onFocusChanged modifiers where FocusState.isCaptured() == true.

When a component is in a Captured state, all focus requests from other components are declined.

Returns

true if the focus was successfully captured by one of the focus modifiers associated with this FocusRequester. False otherwise.

Code Examples

CaptureFocusSample

@Composable
fun CaptureFocusSample() {
    val focusRequester = remember { FocusRequester() }
    var value by remember { mutableStateOf("apple") }
    var borderColor by remember { mutableStateOf(Transparent) }
    TextField(
        value = value,
        onValueChange = {
            value =
                it.apply {
                    if (length > 5) focusRequester.captureFocus() else focusRequester.freeFocus()
                }
        },
        modifier =
            Modifier.border(2.dp, borderColor).focusRequester(focusRequester).onFocusChanged {
                borderColor = if (it.isCaptured) Red else Transparent
            },
    )
}