4

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

但是使用 JetPack composeText我无法仅使用单个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中可行吗?

4

1 回答 1

8

因此,借助@CommonsWare 的评论和本文档 https://developer.android.com/jetpack/compose/text#click-with-annotation

我设法使用AnnotatedString&创建了相同的内容ClickableText。注释是内联添加的,任何人都可以理解。

@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)
                }
            }
        )
    }
于 2021-04-24T14:57:41.460 回答