{% setvar book_path %}/reference/androidx/_book.yaml{% endsetvar %} {% include "_shared/_reference-head-tags.html" %}

FocusChangedModifierKt

public final class FocusChangedModifierKt


Summary

Public methods

static final @NonNull Modifier
onFocusChanged(
    @NonNull Modifier receiver,
    @NonNull Function1<@NonNull FocusStateUnit> onFocusChanged
)

Add this modifier to a component to observe focus state events.

Public methods

onFocusChanged

public static final @NonNull Modifier onFocusChanged(
    @NonNull Modifier receiver,
    @NonNull Function1<@NonNull FocusStateUnit> onFocusChanged
)

Add this modifier to a component to observe focus state events. onFocusChanged is invoked when the focus state changes. The onFocusChanged modifier listens to the state of the first focusTarget following this modifier.

import androidx.compose.foundation.border
import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.Box
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color.Companion.Black
import androidx.compose.ui.graphics.Color.Companion.Green
import androidx.compose.ui.unit.dp

var color by remember { mutableStateOf(Black) }
Box(
    Modifier
        .border(2.dp, color)
        // The onFocusChanged should be added BEFORE the focusable that is being observed.
        .onFocusChanged { color = if (it.isFocused) Green else Black }
        .focusable()
)

Note: If you want to be notified every time the internal focus state is written to (even if it hasn't changed), use onFocusEvent instead.