对于 XML 中声明的视图,我们可以使用SpannableStringBuilder
正如这里提到的https://stackoverflow.com/a/4897412/9715339 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中可能吗?
因此,在@CommonsWare 的评论和撰写文档 https://developer.android.com/jetpack/compose/text/user-interactions#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)
}
}
)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)