提问者:小点点

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


对于以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,
                    )

这在喷气机组合中是可能的吗?


共1个答案

匿名用户

因此,借助@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)
                }
            }
        )
    }