Reputation: 163
Using Jetpack Compose BasicTextField
component, I want to create the following effect:
Initial text
Then input some 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
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!
Upvotes: 16
Views: 9306
Reputation: 131
You can make this. Cursor moves to end after any text change, and it possible to move cursor mannualy.
var str by remember {
mutableStateOf(TextFieldValue(""))
}
TextField(
value = str,
onValueChange = {
str = if (str.text != it.text)
TextFieldValue( text = it.text, selection = TextRange(it.text.length))
else
it
}
)
Upvotes: 0
Reputation: 181
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 }
)
Upvotes: 18
Reputation: 271
The best solution is
TextField(
value = TextFieldValue(
text = textValue,
selection = TextRange(textValue.length). // TextRange(0, textValue.length) -> Select that text in a color
),
onValueChange = {
textValue = it.text
}
)
if it works please make it up
Upvotes: 2
Reputation: 189
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
}
)
Upvotes: 13