Vsevolod Kaganovych
01/11/2022, 4:39 PMTextFieldValue
in TextField
with AnnotatedString
?
Example: I have a ViewModel
from where I observe state. When text changes, I update my state and create a new AnnotatedString
like this
val nokString = getNokString(amount = state.nokAmount)
the getNokString()
looks like this
@Composable
private fun getNokString(amount: String): AnnotatedString {
return buildAnnotatedString {
withStyle(
style = SpanStyle(
fontFamily = MaterialTheme.typography.subtitle1.fontFamily,
fontSize = 40.sp
)
) {
append(amount.ifEmpty { "0" })
}
append(" ")
withStyle(
style = SpanStyle(
fontFamily = MaterialTheme.typography.subtitle1.fontFamily,
fontSize = 14.sp
)
) {
append("NOK")
}
}
}
But when I assign a new value to TextField
TextField(value = TextFieldValue(nokString),
onValueChange = {
actioner.invoke(SendAction.OnNokChanged(it.text))
})
The behaviour is unexpected: it appends the new result to the previous one. And I'm not sure how to handle this situation. Any ideas? Thanks in advance.myanmarking
01/11/2022, 4:43 PMVsevolod Kaganovych
01/11/2022, 4:53 PMstate
with the TextFieldValue
instance? I need to update my state + generate a new value to TextFieldValue
each time the text changes.Zach Klippenstein (he/him) [MOD]
01/11/2022, 5:02 PMVsevolod Kaganovych
01/11/2022, 5:06 PMTextFieldValue
. Any ideas how to achieve this?Vsevolod Kaganovych
01/11/2022, 5:26 PMVisualTransformation
. But this is really strange that I can't decorate string in runtime in TextField. The documentation is not quite clear about it.Rick Regan
01/11/2022, 9:32 PMvar textFieldText by mutableStateOf("")
...
TextField(
value = TextFieldValue(getNokString(textFieldText)),
onValueChange = {
textFieldText = it.text.replaceFirst(" NOK".toRegex(),"")
}
)
You would strip away the annotation each time, including the " NOK" (but I'm not sure how you'd distinguish the 0 you added from one that is typed in the field).