简体   繁体   中英

How to highlight specific word of the text in jetpack compose?

I wanted to know how to highlight the specific part of the text in jetpack compose. I tried Html.fromHtml() like this

Text(text = Html.fromHtml(" <font color='red'> Hello </font> World").toString())

But it didn't work. Is there any way I can do this in compose?

With 1.0.0-beta06 you can use the AnnotatedString to display the text with multiple styles.

Something like:

Text(buildAnnotatedString {
    withStyle(style = SpanStyle(color = Color.Red)) {
        append("Hello")
    }
    append(" World ")
})

在此处输入图像描述

Check this function below. Here paragraph is your string source and searchQuery is the specific text you want to highlight.

This provides you a dynamic state for text and search highlights.

@Composable
    fun getData(): StateFlow<AnnotatedString?> {

        val span = SpanStyle(
            color = MaterialTheme.colorScheme.onPrimaryContainer,
            fontWeight = FontWeight.SemiBold,
            background = MaterialTheme.colorScheme.primaryContainer
        )

        return combine(paragraph, searchQuery) { text, query ->
            buildAnnotatedString {
                var start = 0
                while (text.indexOf(query, start, ignoreCase = true) != -1 && query.isNotBlank()) {
                    val firstIndex = text.indexOf(query, start, true)
                    val end = firstIndex + query.length
                    append(text.substring(start, firstIndex))
                    withStyle(style = span) {
                        append(text.substring(firstIndex, end))
                    }
                    start = end
                }
                append(text.substring(start, text.length))
                toAnnotatedString()
            }
        }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(), null)
    }

You can use AnnotatedString to append each word/section with it's own style or to add different style at any index which is great if you're using a string resource.

For the hello world example you could construct something like this:


val annotatedString = buildAnnotatedString {
    val str = "Hello World" // or stringResource(id = R.string.hello_world)
    val boldStr = "Hello" // or stringResource(id = R.string.hello)
    val startIndex = str.indexOf(boldStr)
    val endIndex = startIndex + boldStr.length
    append(str)
    addStyle(style = SpanStyle(color = Color.Red), start = startIndex, end = endIndex)
}
Text(
    text = annotatedString,
)

你好世界文本与红色的你好字母

Using addStyle in this way allows us to do some fun things like adding multiple styles to the same text

val annotatedString = buildAnnotatedString {
    val str = "Hello Wonderful World" // or stringResource(id = R.string.hello_world)
    val boldStr = "Wonderful World" // or stringResource(id = R.string.world)
    val startIndex = str.indexOf(boldStr)
    val endIndex = startIndex + boldStr.length
    append(str)
    addStyle(style = SpanStyle(color = Color.Red), start = startIndex, end = endIndex)

    val italicsStr = "Wonderful"
    val italicsStartIndex = str.indexOf(italicsStr)
    val italicsEndIndex = startIndex + italicsStr.length
    addStyle(style = SpanStyle(fontStyle = FontStyle.Italic), start = italicsStartIndex, end = italicsEndIndex)
}
Text(
    text = annotatedString,
    style = TextStyle(fontWeight = FontWeight.Bold),
    color = Color.Blue,
)

文本你好美妙的世界,颜色和斜体各不相同

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM