Android Jetpack 撰写 : How to show styled Text from string resources

标签 android kotlin android-jetpack-compose android-jetpack-compose-text

我的 strings.xml 中有一个字符串它针对不同的语言进行了本地化。
每个本地化的字符串都使用 Html 标记进行样式设置。
使用安卓TextView ,通过阅读字符串资源,我能够很好地显示样式文本。
考虑到 Jetpack Compose 当前 (1.0.0-rc02)不支持 Html 标签,我尝试使用 TextViewAndroidView 内可组合以下官方文档: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/

相关文章:

java - 为我的应用程序创建教程

android - 在 DrawerLayout 中添加 RecyclerView

android - 启动项目时出现无法理解的错误(gradle)

kotlin - 函数引用和 lambda

android - 在 Jetpack Compose LazyColumn 项目中检测到点击手势时返回错误的项目

android - 我可以在 @Composable 之外使用 Jetpack 撰写图标吗?

android - Jetpack Compose X.dp 性能问题?

Android:如何在没有 Activity 的情况下注册内容观察者?

android - RxJava 在主线程中运行部分平面图

spring - 如何避免在执行长时间运行计算的 Spring WebFlux Controller 中使用 Kotlin Coroutines 的 GlobalScope