我有一个包含html的字符串,如何在Jetpack compose Text中显示它?
在TextView中,我会使用Spanned,并做一些类似的事情:
TextView.setText(Html.fromHtml("<p>something", HtmlCompat.FROM_HTML_MODE_LEGACY)
如何使用Jetpack compose中的文本来完成此操作?
与Yhondi的答案相同,但如果您的目标是api,请使用HtmlCompat>24:
@Composable
fun Html(text: String) {
AndroidView(factory = { context ->
TextView(context).apply {
setText(HtmlCompat.fromHtml(text, HtmlCompat.FROM_HTML_MODE_LEGACY))
}
})
}
我用这种方式完成了它,而不是在AndroidView中使用TextView,它似乎对我很有效
@Composable
fun ExpandingText(
description: String,
modifier: Modifier = Modifier,
textStyle: TextStyle = MaterialTheme.typography.body2,
expandable: Boolean = true,
collapsedMaxLines: Int = 3,
expandedMaxLines: Int = Int.MAX_VALUE,
) {
val text = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(description, Html.FROM_HTML_MODE_LEGACY)
} else {
HtmlCompat.fromHtml(description, HtmlCompat.FROM_HTML_MODE_LEGACY)
}
var canTextExpand by remember(text) { mutableStateOf(true) }
var expanded by remember { mutableStateOf(false) }
val interactionSource = remember { MutableInteractionSource() }
Text(
text = text.toString(),
style = textStyle,
overflow = TextOverflow.Ellipsis,
maxLines = if (expanded) expandedMaxLines else collapsedMaxLines,
modifier = Modifier
.clickable(
enabled = expandable && canTextExpand,
onClick = { expanded = !expanded },
indication = rememberRipple(bounded = true),
interactionSource = interactionSource,
)
.animateContentSize(animationSpec = spring())
.then(modifier),
onTextLayout = {
if (!expanded) {
canTextExpand = it.hasVisualOverflow
}
}
)
}
不幸的是,Jetpack-compose还不支持HTML。。。
所以,你可以做的是:
选项1:创建自己的HTML解析器
Jetpack-compose支持粗体、颜色、字体等基本样式。因此,您可以循环浏览原始HTML文本并手动应用文本样式。
选项2:将旧的TextView
集成到您的Jetpack组合中
请阅读:在你的应用中采用Compose
谢谢。
您可以将旧的TextView集成到Jetpack中,如下所示:
AndroidView(factory = { context ->
TextView(context).apply {
text = Html.fromHtml(your_html)
}
})
更多信息:https://foso.github.io/Jetpack-Compose-Playground/viewinterop/androidview/
您可以使用以下代码:
@Composable
private fun TextHtml() {
Text(text = buildAnnotatedString {
withStyle(style = SpanStyle(color = Gray600)) {
append("normal text")
}
withStyle(style = SpanStyle(fontWeight = FontWeight.Bold,color = Gray700)) {
append("bold text ")
}
})
}
使用withStyle应用html标记,并在其中使用append((添加字符串