Autoselect TextField text on focus

Viewed 303

I want to have a TextField where the entire text automatically gets selected when the user taps it (so they can replace it all without pressing delete).

Because onFocusChanged (and onTextInputStarted) are called before onValueChange, and onValueChange is always called on focus, I have to prevent running onValueChange once. Here's how I did it using a variable (valueChangeLock):

var value by remember { mutableStateOf(TextFieldValue("")) }

// onValueChange is called after onFocusChanged, overriding the selection in onFocusChanged.
// Fix: Lock onValueChange when calling onFocusChanged
var valueChangeLock = false
BasicTextField(
    value = value,
    onValueChange = {
        if (valueChangeLock) {
            valueChangeLock = false
        } else {
            value = TextFieldValue(it.text, TextRange(it.text.length))
        }
    },
    modifier = modifier.onFocusChanged {
        if (it.isFocused) {
            valueChangeLock = true
            tfValue = TextFieldValue(value, TextRange(0, value.length))
        }
    },
)

Is there a better way to implement this?

1 Answers

You could use the Modifier.clickable interface to simplify this.

modifier = modifier.clickable {
    valueChangeLock = true
    tfValue = TextFieldValue(value, TextRange(0, value.length))
}

Also consider wrapping your text in a SelectionContainer

Related