freeFocus

Function

Common
fun FocusRequesterModifierNode.freeFocus(): Boolean

Use this function to send a request to free focus when one of the components associated with this FocusRequester is in a Captured state. If a component frees focus, it will send a FocusState object to its associated onFocusChanged modifiers where FocusState.isCaptured() == false.

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

Returns

true if the captured focus was successfully released. i.e. At the end of this operation, one of the components associated with this focusRequester freed focus.

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
            },
    )
}