0 string android android-studio android-jetpack-compose
直到最近,我一直使用 XML 来创建屏幕,并且我知道如何使用这些 XML 使某些 TextView 可单击。
现在,我正在过渡到专门使用 Jetpack Compose,不再依赖 XML。
我目前正在尝试做的是让文本的一部分有一个关键字(如果单击)可以让您转到应用程序上的另一个屏幕。
例如,如果我的文本显示“ Click here to go to the second screen”,那么当您单击“此处”时,它应该会将您带到另一个屏幕。我查看了 Compose 的在线资源,其中建议使用ClickableText,但这使得整个句子可点击,同时只是使“此处”具有不同的颜色,这不是我想要的。
对于撰写,对我来说,拥有一个可以包含上面的句子但只有一个单词(“此处”)可点击并执行点击操作的文本的最佳方式是什么?
您可以通过 实现上述目标buildAnnotatedString。在这里定义您的文本并传入可点击的文本
@Composable
fun SpannableTextScreen() {
val text = buildAnnotatedString {
append("Click ")
pushStringAnnotation(tag = "click", annotation = "click")
withStyle(
SpanStyle(
textDecoration = TextDecoration.Underline,
color = Color.Red
)
) {
append("here ")
}
pop()
append("to go to the second screen")
}
val context = LocalContext.current
Box(
modifier = Modifier
.fillMaxSize()
.padding(horizontal = 20.dp),
contentAlignment = Alignment.Center
) {
ClickableText(text = text, onClick = { offset ->
text.getStringAnnotations(tag = "click", start = offset, end = offset).firstOrNull()
?.let {
// on click operation here
Toast.makeText(context, "hey", Toast.LENGTH_SHORT).show()
}
})
}
}
Run Code Online (Sandbox Code Playgroud)
只能here点击文字,现在点击heretoast就会显示,可以根据自己的需求修改
| 归档时间: |
|
| 查看次数: |
1002 次 |
| 最近记录: |