May*_*jra 17 android kotlin android-jetpack-compose android-compose-textfield
对于 XML 中声明的视图,我们可以使用SpannableStringBuilder此处提到的/sf/answers/342818871/ 来为部分字符串着色。
但是使用 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,
)
Run Code Online (Sandbox Code Playgroud)
这在jetpack compose中可能吗?
May*_*jra 26
因此,在 @CommonsWare 的评论和Compose 文档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)
}
}
)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14832 次 |
| 最近记录: |