Compose 富文本样式

543 阅读1分钟

富文本样式

Text(
    text = buildAnnotatedString {
        withStyle(style = SpanStyle(color = Color.Black)) {
            append("文字变色加粗")
        }
        withStyle(style = SpanStyle(color = Color.Blue,fontWeight = FontWeight.W900)) {
            append("Jetpack Compose")
        }
        append("\n")
        withStyle(style = SpanStyle(color = Color.Black)) {
            append("文字变色加粗添加下划线")
        }
        withStyle(style = SpanStyle(color = Color.Blue,fontWeight = FontWeight.W900, textDecoration = TextDecoration.Underline)) {
            append("Jetpack Compose")
        }
    }
)

富文本增加点击事件

@Composable
fun Greeting() {
    //文本内容
    val annotatedString = buildAnnotatedString {
        withStyle(style = SpanStyle(color = Color.Black)) {
            append("跳转到官网:")
        }
        pushStringAnnotation(tag = "juejin", annotation = "https://juejin.cn/")
        withStyle(style = SpanStyle(color = Color.Blue, fontWeight = FontWeight.W900)) {
            append("juejin")
        }
        pop()
        append("\n")
        withStyle(style = SpanStyle(color = Color.Black)) {
            append("跳转到官网:")
        }
        pushStringAnnotation(tag = "baidu", annotation = "https://www.baidu.com/")
        withStyle(
            style = SpanStyle(color = Color.Blue, fontWeight = FontWeight.W900)
        ) {
            append("baidu")
        }
        pop()
    }
    //可点击的文本控件
    ClickableText(
        text = annotatedString,
        onClick = { offset ->
            annotatedString.getStringAnnotations(tag = "juejin", start = offset, end = offset)
                .firstOrNull()?.let { annotation ->
                    //跳转到掘金官网
                    val uri = Uri.parse(annotation.item)
                    val intent = Intent(Intent.ACTION_VIEW, uri)
                    startActivity(intent)
                }
            annotatedString.getStringAnnotations(tag = "baidu", start = offset, end = offset)
                .firstOrNull()?.let { annotation ->
                    //跳转到百度官网
                    val uri = Uri.parse(annotation.item)
                    val intent = Intent(Intent.ACTION_VIEW, uri)
                    startActivity(intent)
                }
        }
    )
}

使用可点击的文本ClickableText,pop()是AnnotatedString的方法,作用是结束添加的style和annotation,让文本恢复默认样式。