@Composable
fun BaseScreen(){
Column(modifier = Modifier
.background(color = colorResource(id = R.color.white)).fillMaxSize(),
verticalArrangement = Arrangement.Center, //垂直居中
horizontalAlignment = Alignment.CenterHorizontally//水平居中
){
val firstText="9935472821"
val styleText= buildAnnotatedString {
withStyle(
SpanStyle(
color = colorResource(id = R.color.color_333333),
fontSize = 14.sp
)
){
append("第一行内容\n")
}
withStyle(
SpanStyle(
color = colorResource(id = R.color.c_2776ff),
fontSize = 18.sp,
background = colorResource(id = R.color.black),
)
) {
pushStringAnnotation("onClickOne",annotation = "点击事件一")
append("第二行内容\n")
}
pushStringAnnotation("onClickTwo",annotation = firstText)
append(firstText) //默认ClickableText中设置的style样式
}
ClickableText(
text =styleText ,
//TextView中默认样式
style=TextStyle(
color = colorResource(id = R.color.c_1eb184),
fontSize = 20.sp,
fontWeight = FontWeight.Bold
),
onClick ={
//点击事件一
styleText.getStringAnnotations(tag = "onClickOne",start = it,end = it)
.firstOrNull()?.let { Toast.makeText(applicationContext, "第二行内容", Toast.LENGTH_SHORT).show() }
//点击事件二
styleText.getStringAnnotations(tag = "onClickTwo",start = it,end = it)
.firstOrNull()?.let { Toast.makeText(applicationContext, firstText, Toast.LENGTH_SHORT).show(); }
} )
}
}
效果:
封装:
@Composable
fun SpanText(list: List, modifier: Modifier = Modifier) {
val spanText = buildAnnotatedString {
repeat(list.size) {
val item = list[it]
withStyle(item.spanStyle) {
pushStringAnnotation(“onClick_KaTeX parse error: Expected group after '_' at position 14: it", "onClick_̲it”)
append(item.text)
}
}
}
ClickableText(text = spanText, modifier = modifier, onClick = {
repeat(list.size) { index ->
spanText.getStringAnnotations(tag = “onClick_$index”, start = it, end = it)
.firstOrNull()
?.let { list[index].clicker.invoke() }
}
})
}
data class SpanTextBean(
val text: String = “”,
val spanStyle: SpanStyle = SpanStyle(color = QwerAppColor.c333333, fontSize = 12.sp),
val clicker: () -> Unit = {}
)