Android 部分为文本上色,并使其在Jetpack Compose中可单击
对于XML中声明的视图,我们可以使用这里提到的Android 部分为文本上色,并使其在Jetpack Compose中可单击,android,android-jetpack-compose,android-jetpack-compose-text,Android,Android Jetpack Compose,Android Jetpack Compose Text,对于XML中声明的视图,我们可以使用这里提到的SpannableStringBuilder为部分字符串着色 但是使用JetPack composeText我无法仅使用单个Text实现同样的效果 我想要这样的东西 正如您所看到的,只有“注册”文本具有不同的颜色,而且我想使其可点击 这就是我的文本代码目前的样子 Text(text = "Don't have an account? Sign Up", modifier = Mod
SpannableStringBuilder
为部分字符串着色
但是使用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中可能吗?因此,借助@commonware的评论和本文档 我使用
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)
}
}
)
}
对于单独的颜色方面,您需要查找
AnnotatedString
。我不知道是否有一种方法可以使该段可点击。@commonware是的,就是这样。谢谢你给我指明了正确的方向。