我的 strings.xml
中有一个字符串它针对不同的语言进行了本地化。
每个本地化的字符串都使用 Html 标记进行样式设置。
使用安卓TextView
,通过阅读字符串资源,我能够很好地显示样式文本。
考虑到 Jetpack Compose 当前 (1.0.0-rc02)
不支持 Html 标签,我尝试使用 TextView
在 AndroidView
内可组合以下官方文档:https://developer.android.com/jetpack/compose/interop/interop-apis#views-in-compose
我试过的例子:
@Composable
fun StyledText(text: String, modifier: Modifier = Modifier) {
AndroidView(
modifier = modifier,
factory = { context -> TextView(context) },
update = {
it.text = HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_COMPACT)
}
)
}
strings.xml
中的文字文件:<string name="styled_text">Sample text with <b>bold styling</b> to test</string>
但是,使用 stringResource(id = R.string.styled_text)
提供文本 没有 Html 标签。有没有办法显示文字来自字符串资源 在 Jetpack Compose 中使用 Html 样式?
以下两个问题类似,但它们是不要从资源中读取字符串:
Jetpack compose display html in text
Android Compose: How to use HTML tags in a Text view
最佳答案
stringResource
在引擎盖下使用 resources.getString
,它会丢弃任何样式信息。您需要创建类似 textResource
的内容获取原始值:
@Composable
@ReadOnlyComposable
fun textResource(@StringRes id: Int): CharSequence =
LocalContext.current.resources.getText(id)
并像这样使用它:StyledText(textResource(id = R.string.foo))
@Composable
fun StyledText(text: CharSequence, modifier: Modifier = Modifier) {
AndroidView(
modifier = modifier,
factory = { context -> TextView(context) },
update = {
it.text = text
}
)
}
关于Android Jetpack 撰写 : How to show styled Text from string resources,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68549248/