Compose基础组件:Text
使用
1.加载文本、文本样式
(1)加载普通文本和字符串资源文本
Text(text = "文本文本")
Text(text = "显示字符串资源${stringResource(id = R.string.app_name)}")
(2)设置文本样式
(2.1)通过style参数的TextStyle属性设置文本样式,文本阴影
Text(
text = "通过TextStyle设置样式",
modifier = Modifier
.padding(10.dp),
style = TextStyle(
fontSize = 20.sp,//字体大小
fontWeight = FontWeight.W200,//字体权重
color = Color.Red,//字体颜色
fontFamily = FontFamily.Default,//字体
fontStyle = FontStyle.Italic,//字体样式
shadow = Shadow(//文本阴影
Color.Yellow,
offset = Offset(5.0f, 10.0f),
blurRadius = 3.0f
)
)
)
(2.2)Text参数设置文本样式
Text(
text =
"softWrap - whether the text should break at soft line breaks. If false, the glyphs in " +
"the text will be positioned as if there was unlimited horizontal space. " +
"If softWrap is false, overflow and TextAlign may have unexpected effects",//文本
modifier = Modifier
.padding(10.dp)
.fillMaxWidth(),
color = Color.Green,//文本颜色
fontSize = 20.sp,//文本字体大小
fontStyle = FontStyle.Italic,//文本样式 正常、倾斜
fontWeight = FontWeight.Bold,//文本权重
fontFamily = FontFamily.Serif,//文本字体
letterSpacing = 3.sp,//字符间距
textDecoration = TextDecoration.Underline,//文本装饰 下划线/删除线
textAlign = TextAlign.Start,//文本对其方式
lineHeight = 50.sp,//行高
overflow = TextOverflow.Ellipsis,//文本裁剪
softWrap = true,//是否对某些单词进行换行
minLines = 2,
maxLines = 10,//最大行数
onTextLayout = { textLayoutResult ->
},
)
2.设置文本滚动显示 Modifier.basicMarquee
Row(modifier = Modifier.fillMaxWidth()) {
Text(
text = "您可以将 basicMarquee 修饰符应用于任何可组合项,以产生动画滚动效果。" +
"如果内容太宽,超出可用约束条件,就会出现 Marquee 效果。默认情况下," +
"basicMarquee 会设置特定的配置(例如速度和初始延迟时间),但您可以修改这些参数以自定义效果",
modifier = Modifier.basicMarquee(
iterations = 3,//滚动次数,默认3
animationMode = MarqueeAnimationMode.Immediately,//开始动画的模式,立即开始/当获取焦点时开始
velocity = 50.dp,//滚动速度 默认30.dp
initialDelayMillis = 2000,//初始延迟多少毫秒开始滚动
repeatDelayMillis = 1000,//重复下一次滚动延时多少毫秒开始滚动
),
fontSize = 18.sp
)
}
自定义滚动文本样式
Text("文本文本文本文本文本文本文本文本文本文本文本",
modifier = Modifier
.widthIn(max = edgeWidth * 4)
.graphicsLayer { compositingStrategy = CompositingStrategy.Offscreen }
.drawWithContent {
drawContent()
drawFadedEdge(leftEdge = true)
drawFadedEdge(leftEdge = false)
}
.basicMarquee(
// Animate forever.
iterations = Int.MAX_VALUE,
spacing = MarqueeSpacing(0.dp)//距离下一次滚动文本的间隔距离
)
.padding(start = edgeWidth))
//drawFadedEdge方法
val edgeWidth = 32.dp
fun ContentDrawScope.drawFadedEdge(leftEdge: Boolean) {
val edgeWidthPx = edgeWidth.toPx()
drawRect(
topLeft = Offset(if (leftEdge) 0f else size.width - edgeWidthPx, 0f),
size = Size(edgeWidthPx, size.height),
brush = Brush.horizontalGradient(
colors = listOf(Color.Transparent, Color.Black),
startX = if (leftEdge) 0f else size.width,
endX = if (leftEdge) edgeWidthPx else size.width - edgeWidthPx
), blendMode = BlendMode.DstIn
)
}
3.文本操作
(1)可被选中的文本 SelectionContainer
SelectionContainer {
Text(text = "可以被选中的文本~~~~~~~")
}
(2)设置文本可点击
Text(text = "普通文本可点击",
modifier = Modifier
.padding(10.dp)
.clickable {
"普通文本点击".showToast()
})
Text(
text = "普通文本可点击(去除点击阴影)",
modifier = Modifier
.padding(10.dp)
.clickable(
onClick = {
"普通文本点击(去除点击阴影)".showToast()
},
indication = null,
interactionSource = MutableInteractionSource()
)
)
4.文本中多种样式和操作
(1)文本中包含多种样式
使用buildAnnotatedString、 withStyle
Text(
buildAnnotatedString {
append("文本中多种样式:")
withStyle(
style = SpanStyle(
color = Color.Red,
fontSize = 20.sp,
fontWeight = FontWeight.Bold
)
) {
append("明天")
}
append("去")
withStyle(
style = SpanStyle(
color = Color.Blue,
fontSize = 20.sp,
fontWeight = FontWeight.W200
)
) {
append("哪里?!")
}
},
modifier = Modifier.padding(10.dp)
)
(2)设置文本中部分可点击
使用buildAnnotatedString构建文本,将文本传入ClickableText
val textContent = buildAnnotatedString {
append("登录即代表同意")
pushStringAnnotation(
tag = "tag",
annotation = "点击了隐私政策"
)
withStyle(
style = SpanStyle(
color = Color.Green,
fontSize = 18.sp,
textDecoration = TextDecoration.Underline
)
) {
append("《隐私政策》")
}
pop()
}
ClickableText(text = textContent, onClick = { offset ->
textContent.getStringAnnotations(tag = "tag", start = offset, end = offset)
.firstOrNull()?.let { content ->
//点击可点击部分的逻辑
Toast.makeText(context, content.item, Toast.LENGTH_SHORT).show()
}
})
(3)设置部分文本可点击打开网页链接
val uriHandler = LocalUriHandler.current
Text(
buildAnnotatedString {
append("后面的是个链接:")
val link =
LinkAnnotation.Url(
"https://xxxx.com",
TextLinkStyles(SpanStyle(color = Color.Blue))
) {
val url = (it as LinkAnnotation.Url).url
// log some metrics
uriHandler.openUri(url)
}
withLink(link) { append("《我是链接》") }
},
modifier = Modifier
.fillMaxWidth()
.padding(10.dp)
)
(4)文本加载包含链接的Html
val htmlText: String = """
<h1>温馨提示</h1>
<p>
请确认该 <b>证明</b> 是有效的 <a href="https://www.xxx.com">证明</a>
</p>
""".trimIndent()
Text(
AnnotatedString.fromHtml(
htmlString = htmlText,
linkStyles = TextLinkStyles(
style = SpanStyle(
color = Color.Red,
textDecoration = TextDecoration.Underline,
fontStyle = FontStyle.Italic,
fontSize = 18.sp
),
focusedStyle = SpanStyle(
color = Color.Green,
fontSize = 18.sp
),
hoveredStyle = SpanStyle(
color = Color.Blue,
fontSize = 18.sp
),
pressedStyle = SpanStyle(
color = Color.Yellow,
fontSize = 30.sp
)
)
),
modifier = Modifier.padding(10.dp)
)
5.更多文本样式
(1)使用Brush高级样式
val colorList =
listOf(Color.Red, Color.Yellow, Color.Green, Color.Blue, Color.Magenta, Color.Cyan)
Text(
text = "TextLayoutResult object that callback provides contains paragraph " +
"information, size of the text, baselines and other details. " +
"The callback can be used to add additional " +
"decoration or functionality to the text. For example, " +
"to draw selection around the text.",
modifier = Modifier.padding(10.dp),
style = TextStyle(
brush = Brush.linearGradient(
colors = colorList,
tileMode = TileMode.Mirror
)
)
)
(2)段落文本中设置Brush
Text(
buildAnnotatedString {
append("啦啦啦啦啦啦啦啦啦")
withStyle(
style = SpanStyle(
brush = Brush.linearGradient(colorList)
)
) {
append("哈啊啊啊啊啊啊哈哈哈哈")
}
append("呵呵呵呵呵呵呵呵呵呵呵")
},
modifier = Modifier.padding(10.dp)
)