Change background color of clicked sentence in Text

27 views Asked by At

enter image description hereI want to implement a feature where when I click on a specific sentence within this paragraph, the background color of that sentence changes.

I've tried looking into gesture detection and text selection features within Jetpack Compose, but couldn't find a straightforward way to achieve this effect. Can someone please guide me on how to implement this functionality?

1

There are 1 answers

1
Hezy Ziv On

You can split your text into sentences make each clickable and then change the bg color

fun ClickableSentences() {
    val paragraph = "This is the first sentence. This is the second sentence. This is the third sentence."
    
    val sentences = paragraph.split(". ").map { "$it." }

    var selectedSentence by remember { mutableStateOf(-1) }

    Column {
        sentences.forEachIndexed { index, sentence ->
            val backgroundColor = if (index == selectedSentence) Color.LightGray else Color.Transparent

            BasicText(
                text = buildAnnotatedString {
                    withStyle(style = SpanStyle(backgroundColor = backgroundColor)) {
                        append(sentence)
                    }
                },
                modifier = Modifier
                    .clickable { selectedSentence = index }
                    .padding(4.dp)
            )
        }
    }
}