focusable
Common
Modifier in Compose Foundation
Configure component to be focusable via focus system or accessibility "focus" event.
Add this modifier to the element to make it focusable within its bounds.
Last updated:
Installation
dependencies {
implementation("androidx.compose.foundation:foundation:1.8.0-alpha04")
}
Overloads
@Stable
fun Modifier.focusable(
enabled: Boolean = true,
interactionSource: MutableInteractionSource? = null,
)
Parameters
name | description |
---|---|
enabled | Controls the enabled state. When false , element won't participate in the focus |
interactionSource | [MutableInteractionSource] that will be used to emit [FocusInteraction.Focus] when this element is being focused. |
Code Example
FocusableSample
@Composable
fun FocusableSample() {
// initialize focus reference to be able to request focus programmatically
val focusRequester = remember { FocusRequester() }
// MutableInteractionSource to track changes of the component's interactions (like "focused")
val interactionSource = remember { MutableInteractionSource() }
// text below will change when we focus it via button click
val isFocused = interactionSource.collectIsFocusedAsState().value
val text =
if (isFocused) {
"Focused! tap anywhere to free the focus"
} else {
"Bring focus to me by tapping the button below!"
}
Column {
// this Text will change it's text parameter depending on the presence of a focus
Text(
text = text,
modifier =
Modifier
// add focusRequester modifier before the focusable (or even in the parent)
.focusRequester(focusRequester)
.focusable(interactionSource = interactionSource)
)
Button(onClick = { focusRequester.requestFocus() }) {
Text("Bring focus to the text above")
}
}
}