Jetpack Compose——Text(文本)的使用

首先来看一些基础的参数

        Text(text = "hello world", fontSize = 30.sp)//设置字体大小
        Text(
            text = stringResource(id = R.string.hello_world),//设置为资源中的文字
            color = colorResource(id = R.color.purple_500)//设置字体颜色
        )
        Text(text = "HelloWorld", fontStyle = FontStyle.Italic)//设置文字斜体
        Text(text = "Hello World", fontWeight = FontWeight.Bold)//文字粗体
        Text(
            text = "Hello World",
            textAlign = TextAlign.Center,//文字居中对齐
            modifier = Modifier
                .width(150.dp)//控件总宽度
                .background(color = colorResource(id = R.color.teal_200))//控件背景色

        )
        Text(text = "HelloWorld", fontFamily = FontFamily.Serif)//设置字体样式为Serif

设置Text行数及文字溢出

        Text("Hello".repeat(50), maxLines = 1)//设置行数上线,超出直接截断
        Text(
            "Hello".repeat(50),
            maxLines = 1,//设置最大行数
            color = colorResource(id = R.color.purple_200),
            overflow = TextOverflow.Ellipsis//文字溢出,文末显示...
        )

多样式配置Text:

1,Text中个别文字字体及颜色设置

         Text(buildAnnotatedString {//设置多样式字体
            withStyle(style = SpanStyle(color = Color.Blue)) {
                append("H")
            }
            append("ello ")
            withStyle(style = SpanStyle(fontWeight = FontWeight.Bold, color = Color.Red)) {
                append("W")
            }
            append("orld")
        })

 

 2,Text段落样式显示

         Text(buildAnnotatedString {//设置段落样式
            withStyle(style = ParagraphStyle(lineHeight = 30.sp)) {
                withStyle(style = SpanStyle(color = Color.Blue)) {
                    append("Hello \n")
                }
                withStyle(style = SpanStyle(fontWeight = FontWeight.Bold, color = Color.Red)) {
                    append("World")
                }
            }
        })

Text用户精细化互动(长按选择复制)

        SelectionContainer {//用户精细化互动,可以选择复制
            Text(text = "This text is selectable")
        }
        SelectionContainer {//用户精细化互动,可以部分选择复制
            Column {
                Text("This text is selectable")
                Text("This one too")
                Text("This one as well")
                DisableSelection {//该部分停用选择功能,无法复制
                    Text("But not this one")
                    Text("Neither this one")
                }
                Text("But again, you can select this one")
                Text("And this one too")
            }
        }

 

 Text字符添加点击响应

        val annotatedText = buildAnnotatedString {
            append("Click ")
            //设置存放的数据和标签,此处定义的tag要和后面调用的tag保持一致
            pushStringAnnotation(tag = "URL", annotation = "https://baidu.com")
            withStyle(style = SpanStyle(color = Color.Blue, fontWeight = FontWeight.Bold)) {
                append("here")
            }
            append("--------------------->")
            //代表设置标签结束,与pushStringAnnotation结合使用
            pop()
        }
        ClickableText(text = annotatedText, onClick = { offset ->//点击文字的下标
            annotatedText.getStringAnnotations(tag = "URL", start = offset, end = offset)
                //firstOrNull是找List中的第一个对象,找不到则则返回null
                .firstOrNull()?.let { annotation ->
                    Log.d("Click URL", annotation.item)
                }
            Log.d("Click offset", offset.toString())
        })

 Text修改文字

        var text by remember { mutableStateOf("Hello") }
        //默认填充样式修改文字
        TextField(value = text, onValueChange = {text = it},label = { Text("Lable")})
        //轮廓样式修改文字
        OutlinedTextField(value = text, onValueChange = {text = it},label = {Text("Lable")})

到这里基本属性就写完了,下面来个大合集:

@Composable
fun testText() {
    Column(Modifier.padding(20.dp)) {
        Text(text = "hello world", fontSize = 30.sp)//设置字体大小
        Text(
            text = stringResource(id = R.string.hello_world),//设置为资源中的文字
            color = colorResource(id = R.color.purple_500)//设置字体颜色
        )
        Text(text = "HelloWorld", fontStyle = FontStyle.Italic)//设置文字斜体
        Text(text = "Hello World", fontWeight = FontWeight.Bold)//文字粗体
        Text(
            text = "Hello World",
            textAlign = TextAlign.Center,//文字居中对齐
            modifier = Modifier
                .width(150.dp)//控件总宽度
                .background(color = colorResource(id = R.color.teal_200))//控件背景色

        )
        Text(text = "HelloWorld", fontFamily = FontFamily.Serif)//设置字体样式为Serif
        Text(buildAnnotatedString {//设置多样式字体
            withStyle(style = SpanStyle(color = Color.Blue)) {
                append("H")
            }
            append("ello ")
            withStyle(style = SpanStyle(fontWeight = FontWeight.Bold, color = Color.Red)) {
                append("W")
            }
            append("orld")
        })
        Text(buildAnnotatedString {//设置段落样式
            withStyle(style = ParagraphStyle(lineHeight = 30.sp)) {
                withStyle(style = SpanStyle(color = Color.Blue)) {
                    append("Hello \n")
                }
                withStyle(style = SpanStyle(fontWeight = FontWeight.Bold, color = Color.Red)) {
                    append("World")
                }
            }
        })
        Text("Hello".repeat(50), maxLines = 1)//设置行数上线,超出直接截断
        Text(
            "Hello".repeat(50),
            maxLines = 1,//设置最大行数
            color = colorResource(id = R.color.purple_200),
            overflow = TextOverflow.Ellipsis//文字溢出,文末显示...
        )
        SelectionContainer {//用户精细化互动,可以选择复制
            Text(text = "This text is selectable")
        }
        SelectionContainer {//用户精细化互动,可以部分选择复制
            Column {
                Text("This text is selectable")
                Text("This one too")
                Text("This one as well")
                DisableSelection {//该部分停用选择功能,无法复制
                    Text("But not this one")
                    Text("Neither this one")
                }
                Text("But again, you can select this one")
                Text("And this one too")
            }
        }
        val annotatedText = buildAnnotatedString {
            append("Click ")
            //设置存放的数据和标签,此处定义的tag要和后面调用的tag保持一致
            pushStringAnnotation(tag = "URL", annotation = "https://baidu.com")
            withStyle(style = SpanStyle(color = Color.Blue, fontWeight = FontWeight.Bold)) {
                append("here")
            }
            append("--------------------->")
            //代表设置标签结束,与pushStringAnnotation结合使用
            pop()
        }
        ClickableText(text = annotatedText, onClick = { offset ->//点击文字的下标
            annotatedText.getStringAnnotations(tag = "URL", start = offset, end = offset)
                //firstOrNull是找List中的第一个对象,找不到则则返回null
                .firstOrNull()?.let { annotation ->
                    Log.d("Click URL", annotation.item)
                }
            Log.d("Click offset", offset.toString())
        })

        var text by remember { mutableStateOf("Hello") }
        //默认填充样式修改文字
        TextField(value = text, onValueChange = {text = it},label = { Text("Lable")})
        //轮廓样式修改文字
        OutlinedTextField(value = text, onValueChange = {text = it},label = {Text("Lable")})

    }

}

 

要实现跑马灯效果,可以使用`Animatable`和`AnimatableVector`来创建一个自定义的跑马灯效果的`Text`控件。 首先,需要添加以下依赖到你的项目中: ```kotlin implementation "androidx.compose.animation:animation:1.0.0" implementation "androidx.compose.animation:animation-core:1.0.0" implementation "androidx.compose.animation:animation-graphics:1.0.0" ``` 然后,可以创建一个自定义的`MarqueeText`控件,继承自`Text`: ```kotlin import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.* import androidx.compose.animation.core.AnimationConstants.Infinite import androidx.compose.foundation.layout.Box import androidx.compose.material.Text import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.graphics.vector.PathNode import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp @Composable fun MarqueeText( text: String, modifier: Modifier = Modifier, speed: Dp = 100.dp, textColor: Color = Color.Black, backgroundColor: Color = Color.White, ) { var textWidth by remember { mutableStateOf(0f) } var offsetX by remember { mutableStateOf(0f) } var isRunning by remember { mutableStateOf(false) } val infiniteTransition = rememberInfiniteTransition() val animatedValue = animateFloatAsState( targetValue = if (isRunning) -textWidth else 0f, animationSpec = infiniteRepeatable( animation = tween(durationMillis = (textWidth / speed).toInt(), easing = LinearEasing), repeatMode = RepeatMode.Restart, ) ) LaunchedEffect(text) { isRunning = true } Box(modifier = modifier) { Text( text = text, modifier = Modifier.alpha(0f), onTextLayout = { layoutResult -> textWidth = layoutResult.size.width.toFloat() } ) Box( modifier = Modifier.offset(x = animatedValue.value) .onSizeChanged { size -> offsetX = size.width.toFloat() } ) { Text( text = text, modifier = Modifier.offset(x = offsetX), color = textColor, onTextLayout = { layoutResult -> textWidth = layoutResult.size.width.toFloat() } ) } Box( modifier = Modifier.offset(x = animatedValue.value + offsetX) .onSizeChanged { size -> offsetX += size.width.toFloat() } ) { Text( text = text, color = textColor, backgroundColor = animateColorAsState(targetValue = backgroundColor).value, onTextLayout = { layoutResult -> textWidth = layoutResult.size.width.toFloat() } ) } } } ``` 然后,你可以在你的Compose函数中使用`MarqueeText`控件来实现跑马灯效果: ```kotlin @Composable fun MyScreenContent() { MarqueeText( text = "Hello, Jetpack Compose!", modifier = Modifier.fillMaxWidth(), speed = 100.dp, textColor = Color.White, backgroundColor = Color.Blue, ) } ``` 这样,你就可以在你的界面上看到一个带有跑马灯效果的文本了。你可以根据需要调整`speed`来控制跑马灯的速度,`textColor`和`backgroundColor`来设置文本和背景颜色
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值