【问题标题】:Partially color text and make it clickable in Jetpack Compose [duplicate]部分彩色文本并使其在 Jetpack Compose 中可点击 [重复]
【发布时间】:2021-04-24 14:18:05
【问题描述】:

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

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

【问题讨论】:

  • 对于单独的颜色方面,您正在寻找AnnotatedString。我不知道是否有办法使该段可点击。
  • @CommonsWare 是的,就是这样。感谢您为我指明正确的方向。

标签: android android-jetpack-compose android-jetpack-compose-text


【解决方案1】:

所以在@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)
                }
            }
        )
    }

【讨论】:

  • 感谢您提供此示例。当前单击没有标签的文本将抛出 java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 。要更正此问题,您将按照these docs 的指示执行以下操作并使用.firstOrNull()?.let { annotation
  • 感谢pop()“当前标签”上面的评论。我在使用多个推送时遇到了一个问题,无论我点击什么,它只会触发第一个推送的项目。
猜你喜欢
  • 2022-10-21
  • 2021-04-10
  • 1970-01-01
  • 2020-01-28
  • 1970-01-01
  • 1970-01-01
  • 2021-11-07
  • 2015-08-23
  • 2022-11-24
相关资源
最近更新 更多