Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jetpack compose: cursor in the end of a TextField

Using Jetpack Compose BasicTextField component, I want to create the following effect:

Initial text

Initial text

Then input some value

Text with Value

After that, move the cursor for index 2 for example and put a value (let's say 3), in the end. I want the following effect:

Desired effect

Desired effect

In other words, I want that the value is inputted in the current index and force the cursor to the end (and can change the cursor again if I want, and redo the process). I can force the cursor to stay always in the end, but I don't know how to do this in Jetpack compose.

Note: I have tried solutions using TextRange, but this locks my selection

Thanks in advance!

like image 235
IGGI Avatar asked Dec 12 '25 18:12

IGGI


2 Answers

The correct answer to put the cursor at the end AND be able to select, copy, etc. the text in the TextField is:

var textFieldValueState by remember {
    mutableStateOf(
        TextFieldValue(
            text = textValue,
            selection = TextRange(textValue.length)
        )
    )
}

TextField(
    value = textFieldValueState,
    onValueChange = { textFieldValueState = it }
)
like image 75
Aledis Avatar answered Dec 14 '25 08:12

Aledis


To move cursor to a position set the TextRange(position). For example, if you want to move the cursor to end of text do

TextField(
    value = TextFieldValue(
        text = textValue,
        selection = TextRange(textValue.length)
    ),
    onValueChange = {
        textValue = it.text
    }
)
like image 30
Deena Avatar answered Dec 14 '25 06:12

Deena