Nthily
08/20/2023, 4:39 PMBasicTextField
that needs to respond to onValueChange
to update the text, but also needs to respond to some external button clicks to update the text.
For example, if I click an emoji button to select an emoji, I need to insert the shortcode string of the emoji after the current cursor position
, but I can't seem to get the current cursor position of the TextField? 🤔Stylianos Gakis
08/20/2023, 4:51 PMNthily
08/20/2023, 5:16 PMonValueChange
, such as
BasicTextField(
value = viewModel.replyField,
onValueChange = viewModel::updateText
)
and VM :
var replyField by mutableStateOf(TextFieldValue(""))
private set
fun updateText(text: TextFieldValue) { replyField = text }
I need to update this TextFIeldValue elsewhere, like:
EmojiSheet(
...
onSelectEmoji = { shortcode ->
viewModel.updateText(
text = viewModel.replyField.copy(viewModel.replyField.text + shortcode)
)
)
The problem is here, I directly called the vm to update TextFieldValue instead of updating onValueChange in BasicTextField, so I don't know how to insert text after the cursor here. @Stylianos GakisStylianos Gakis
08/20/2023, 5:54 PMJez
08/26/2023, 5:17 PMTextFieldValue
contains a selection property. When you change the text you want to update the selection to be TextRange(<index of the end of the characters you added>)
, in addition to changing the annotatedString property.
something like this in VM, as one approach:
fun appendText(newString: String) {
val newText = replyField.text + newString
replyField = replyField.copy {
text = newText
selection = TextRange(newText.length)
}
}
Note that I’m using copy() here to preserve whatever composition
state the TextFieldValue might currently hold.