'Multi style text editing for TextField composable in android jetpack compose

I want to change the text style (fontSize , color , fontWeight , ...) of a selected text in a TextFiled() composable , with a button in android jetpack compose.

(The main problem is, when i change the text style of a selected text ,the TextField can not save it , or when i add/remove a letter in TextField , the TextField deletes the previous text style.)

In other words, when the recomposition process occurs, the text styles disappears in the TextField()

enter image description here

my code is :

@Composable
fun Show() {

    val inputText = remember{ mutableStateOf(TextFieldValue("This is a annotated text text"))}
    Column(
        modifier = Modifier.fillMaxSize().padding(5.dp) ,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        //=================== TextField
        CustomTextField(textInput = inputText)
        //==================== Button
        Button(onClick = {
            inputText.value = changeSegmentColor(inputText.value)

        }) {
            Text(text = "Change the text style of selected text")
        }
        //======================
    }
}

@Composable
fun CustomTextField (
    textInput:MutableState<TextFieldValue>
) {
    TextField(
        value = textInput.value , onValueChange = {
            textInput.value = it
        },
        modifier = Modifier.fillMaxWidth().heightIn(min = 200.dp) ,
    )
}
private fun changeSegmentColor(textFVal: TextFieldValue):TextFieldValue{
    val txtAnnotatedBuilder = AnnotatedString.Builder()
    val realStartIndex = textFVal.getTextBeforeSelection(textFVal.text.length).length
    val endIndex = realStartIndex + textFVal.getSelectedText().length
    txtAnnotatedBuilder.append(textFVal.annotatedString)
    val myStyle = SpanStyle(
        color = Color.Red ,
        fontSize = 16.sp ,
        background = Color.Green
    )
    txtAnnotatedBuilder.addStyle(myStyle ,realStartIndex ,endIndex)
    return textFVal.copy(annotatedString = txtAnnotatedBuilder.toAnnotatedString())
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source