android:selectAllOnFocus in Jetpack Compose TextField

Viewed 314

Traditional EditText on Android supports android:selectAllOnFocus attribute, which causes its content to be selected when user, for example, clicks on the EditText.

How can this behavior be achieved when using androidx.compose.material.TextField in Jetpack Compose?

1 Answers

You can collect the focus state from MutableInteractionSource and change the selection state depending on it:

var textFieldValue by remember { mutableStateOf(TextFieldValue("Lorem ipsum")) }
val interactionSource = remember { MutableInteractionSource() }
val isFocused by interactionSource.collectIsFocusedAsState()
LaunchedEffect(isFocused) {
    textFieldValue = textFieldValue.copy(
        selection = if (isFocused) {
            TextRange(
                start = 0,
                end = textFieldValue.text.length
            )
        } else {
            TextRange.Zero,
        }
    )
}
TextField(
    value = textFieldValue,
    onValueChange = { textFieldValue = it },
    interactionSource = interactionSource,
)
Related