4

I'm trying make BasicTextField select all contents when user taps on it.

This happens automatically if user will long press on the contents of BasicTextField but I want it happening without the long press. There's a thread Select all text of TextField in Jetpack Compose but it utilizes TextFieldValue object which is hidden in BasicTextField but can be passed in TextField composable.

1 Answer 1

3

You can use the TextFieldValue also with a BasicTextField.

Instead of using the onFocusChanged modifier you can use the interactionSource and change the selection range depending on it.

Something like:

var textFieldValue by remember { mutableStateOf(TextFieldValue("Custom text")) }
val interactionSource = remember { MutableInteractionSource() }
val isFocused by interactionSource.collectIsFocusedAsState()

LaunchedEffect(isFocused) {

    val endRange = if (isFocused) textFieldValue.text.length else 0

    textFieldValue = textFieldValue.copy(
        selection = TextRange(
                start = 0,
                end = endRange
            )
    )
}

BasicTextField(
    value = textFieldValue,
    onValueChange = { textFieldValue = it },
    interactionSource = interactionSource
)
1
  • 1
    Thanks, I somehow missed the overload because of the onValueChange Nov 10, 2022 at 19:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.