So the feature I want is that I want to select the text and should be able to bold it or make it italic etc.
I am using following code to achieve that:
var annotatedString = remember { mutableStateOf(AnnotatedString("")) }
var textFieldValue =
remember { mutableStateOf<TextFieldValue>(TextFieldValue(annotatedString.value)) }
fun makeTextBold(textFieldValue: MutableState<TextFieldValue>) {
val selection = textFieldValue.value.selection
if (!selection.collapsed) {
val annotatedString = buildAnnotatedString {
append(textFieldValue.value.annotatedString.subSequence(0, selection.start))
withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) {
append(
textFieldValue.value.annotatedString.subSequence(
selection.start,
selection.end
)
)
}
append(
textFieldValue.value.annotatedString.subSequence(
selection.end,
textFieldValue.value.annotatedString.length
)
)
}
textFieldValue.value = textFieldValue.value.copy(annotatedString)
}
}
Then I use my textFieldValue in TextField
TextField(
value = textFieldValue.value,
onValueChange = { textFieldValue.value = it },
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
)
The problem with this code is it only makes it bold when the text is selected, when I deselect the text , text becomes normal again (not bold). What am I doing wrong ?
1
This is a known bug reported on the Google Issue Tracker. Please upvote it and leave a comment there to draw more attention to it.
The problem is that the applied SpanStyle
s are not present in the TextFieldValue
that is supplied in the onValueChange
callback. So whenever the onValueChange
callback is invoked, you will overwrite your current annotatedString
with an annotatedString
without any SpanStyle
s.
Besides that, your annotatedString
variable is actually redundant:
val textFieldValue = remember {
mutableStateOf(TextFieldValue(AnnotatedString("")))
}