微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

部分着色文本并使其在 Jetpack Compose 中可点击

如何解决部分着色文本并使其在 Jetpack Compose 中可点击

对于在 XML 中声明的视图,我们可以使用此处提到的 SpannableStringBuilder https://stackoverflow.com/a/4897412/9715339 为该部分字符串着色。

但是使用 JetPack compose Text 我无法仅使用单个 Text 来实现相同的效果

我想要这样的东西。

Partial color text

正如您所看到的,只有“注册”文本具有不同的颜色,而且我想让它可点击

这是我的文本代码目前的样子

Text(text = "Don't have an account? Sign Up",modifier = Modifier.align(Alignment.BottomCenter),style = MaterialTheme.typography.h6,color = MaterialTheme.colors.secondary,)

这在 jetpack compose 中可行吗?

解决方法

所以在@CommonsWare 的评论和本文档的帮助下 https://developer.android.com/jetpack/compose/text#click-with-annotation

我设法使用 AnnotatedStringClickableText 创建了相同的内容。注释是内嵌添加的,以便任何人都能理解。

@Composable
    fun AnnotatedClickableText() {
        val annotatedText = buildAnnotatedString {
            //append your initial text
            withStyle(
                style = SpanStyle(
                    color = Color.Gray,)
            ) {
                append("Don't have an account? ")

            }

            //Start of the pushing annotation which you want to color and make them clickable later
            pushStringAnnotation(
                tag = "SignUp",// provide tag which will then be provided when you click the text
                annotation = "SignUp"
            )
            //add text with your different color/style
            withStyle(
                style = SpanStyle(
                    color = Color.Red,)
            ) {
                append("Sign Up")
            }
            // when pop is called it means the end of annotation with current tag
            pop()
        }

        ClickableText(
            text = annotatedText,onClick = { offset ->
                annotatedText.getStringAnnotations(
                    tag = "SignUp",// tag which you used in the buildAnnotatedString
                    start = offset,end = offset
                )[0].let { annotation ->
                    //do your stuff when it gets clicked
                    Log.d("Clicked",annotation.item)
                }
            }
        )
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。