Android Compose实现一段可点击的超链接文本,Compose的实现方式与在Activity或Fragment中的实现方式是有所不同的,因此记录一下Android Compose实现可点击的超链接文本。代码如下:
首先定义一段字符串数组:
<!-- 可供多语言 -->
<string-array name="arrays">
<item>Agree to the </item> <!--   是一个英文半角空格占位符 -->
<item>User Agreements</item>
<item> and the </item>
<item>Privacy Policy</item>
<item>. </item>
</string-array>
@Composable
fun test() {
val agreements = stringArrayResource(id = R.array.arrays)
val color = Color.Blue // 超链接颜色
val annotatedString = buildAnnotatedString {
for(str in agreements) {
when(str) {
"User Agreements"-> {
pushStringAnnotation(tag="agreement", annotation = "https://abc")
withStyle(style = SpanStyle(color = color, fontWeight = FontWeight.Bold)){
append(str)
}
pop() // 使用Push之后,需要pop,否则点击时tag标签获取不到
}
"Privacy Policy" -> {
pushStringAnnotation(tag="privacy", annotation = "https://def")
// 设置
withStyle(style = SpanStyle(color = color, fontWeight = FontWeight.Bold)){
append(str)
}
pop()
}
else -> append(str)
}
}
}
val style = LocalTextStyle.current.copy(textIndent = TextIndent(firstLine = 24.sp)) // textIndent是首行缩进24.sp
ClickableText(text = annotatedString, modifier = Modifier
.padding(top = 8.dp)
.alpha(0.65f), style = style, onClick = { offset ->
// 获取标签
annotatedString.getStringAnnotations(tag = "privacy", start = offset, end = offset).firstOrNull()?.let {
val title = annotatedString.text.subSequence(it.start, it.end)
val url = it.item
Log.i(TAG, "test-->: $offset $title $url")
// 可以实现其它逻辑
}
annotatedString.getStringAnnotations(tag = "agreement", start = offset, end = offset).firstOrNull()?.let {
val title = annotatedString.text.subSequence(it.start, it.end)
val url = it.item
Log.i(TAG, "test-->: $offset $title $url")
// 可以实现其它逻辑
}
})
}
注:strings.xmls中需使用的各种空格占位符
 (普通的英文半角空格)
 (普通的英文半角空格但不换行)
 (中文全角空格,就是一个中文宽度)
 (半个中文宽度)
 (一个中文宽度)
 (四分之一中文宽度)