AndroidCompose布局,一个Text写多种字体样式和点击事件

108 阅读1分钟

@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<SpanTextBean>,
    modifier: Modifier = Modifier,
    textStyle: TextStyle = TextStyle(fontStyle = FontStyle.Normal)
) {
    val spanText = buildAnnotatedString {
        repeat(list.size) {
            val item = list[it]
            withStyle(item.spanStyle) {
                pushStringAnnotation("onClick_$it", "onClick_$it")
                append(item.text)
            }
        }
    }
    ClickableText(text = spanText, modifier = modifier, style = textStyle, 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 = Color.black, fontSize = 12.sp),
    val clicker: () -> Unit = {}
)