Thread
#compose
    Luis Daivid

    Luis Daivid

    10 months ago
    Is it possible to move cursor to end position in TextField with initial value? I set it to the end of the text using TextFieldValue’s selection, and the cursor stays fixed at the last position even if the user clicks in the middle of the text. What I want is for the cursor to be positioned at the last position only when it is first focused, and the user should be able to move the cursor.
    Zoltan Demant

    Zoltan Demant

    10 months ago
    I do this and it works just fine! 🙂
    var textFieldValueState by remember {
        mutableStateOf(
            TextFieldValue(
                text = valueOrEmpty,
                selection = TextRange(
                    index = valueOrEmpty.length
                )
            )
        )
    }
    Luis Daivid

    Luis Daivid

    10 months ago
    @Zoltan Demant This way, although the cursor is at the end, I don’t think it will move to the middle when user click the middle of the text.
    Zoltan Demant

    Zoltan Demant

    10 months ago
    It does! Just make sure you pass it into the TextField variant that accepts a TextFieldValue (rather than plain string) and only update it with
    .copy
    instead of assigning a new TextFieldValue.
    Luis Daivid

    Luis Daivid

    10 months ago
    @Zoltan Demant I didn’t understand. Even if the user selects the middle of the text, the length of valueOrEmpty remains the same, so isn’t the cursor still at the end?
    Zoltan Demant

    Zoltan Demant

    10 months ago
    You would update the text as the user types, so valueOrEmpty would be something like "Hello world" at that point!
    You get a new
    TextFieldValue
    in
    onValueChange
    anytime the user types anything:
    onValueChange = { newValue ->
        textFieldValueState = newValue
    }
    Luis Daivid

    Luis Daivid

    10 months ago
    @Zoltan Demant However, when the user touches in front of w, onValueChange will not be called, and even if called, “Hello world”.length is still 11, so the cursor is not the same?
    Zoltan Demant

    Zoltan Demant

    10 months ago
    The TextFieldState gets passed around quite a bit inside TextField implementations, I cant exactly tell where the cursor position gets updated, but you will receive an
    onValueChange
    callback anytime it does, and as long as you update your remembered textFieldValue - the cursor will move accordingly (Im using this in a beta version of my app and it works).
    Luis Daivid

    Luis Daivid

    10 months ago
    Oh, I see. newValue holds the index of the cursor when the user touches it, so we need to copy the newValue. Thank you. It was very helpful.