Is it possible to move cursor to end position in T...
# compose
l
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.
🙌 1
z
I do this and it works just fine! 🙂
Copy code
var textFieldValueState by remember {
    mutableStateOf(
        TextFieldValue(
            text = valueOrEmpty,
            selection = TextRange(
                index = valueOrEmpty.length
            )
        )
    )
}
l
@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.
z
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.
l
@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?
🙌 1
z
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:
Copy code
onValueChange = { newValue ->
    textFieldValueState = newValue
}
l
@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?
z
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).
🙌 1
l
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.
🙏🏽 1
951 Views