kotlin Android Jetpack组成:如何显示字符串资源中的样式化文本

q0qdq0h2  于 2023-10-23  发布在  Kotlin
关注(0)|答案(4)|浏览(113)

我在strings.xml中有一个字符串,它被本地化为不同的语言。每个本地化的字符串都使用Html标记进行样式化。
使用AndroidTextView,我能够通过阅读字符串资源来显示样式化的文本。
考虑到Jetpack Compose目前不支持Html标签,我尝试在AndroidView composable中使用TextView,以下是官方声明: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

3bygqnnd

3bygqnnd1#

目前正在讨论如何在Jetpack Compose UI上实现:https://issuetracker.google.com/issues/139320238
经过一些研究,我想出了以下解决方案,我也在同一个讨论中发布:

@Composable
@ReadOnlyComposable
private fun resources(): Resources {
    LocalConfiguration.current
    return LocalContext.current.resources
}

fun Spanned.toHtmlWithoutParagraphs(): String {
    return HtmlCompat.toHtml(this, HtmlCompat.TO_HTML_PARAGRAPH_LINES_CONSECUTIVE)
        .substringAfter("<p dir=\"ltr\">").substringBeforeLast("</p>")
}

fun Resources.getText(@StringRes id: Int, vararg args: Any): CharSequence {
    val escapedArgs = args.map {
        if (it is Spanned) it.toHtmlWithoutParagraphs() else it
    }.toTypedArray()
    val resource = SpannedString(getText(id))
    val htmlResource = resource.toHtmlWithoutParagraphs()
    val formattedHtml = String.format(htmlResource, *escapedArgs)
    return HtmlCompat.fromHtml(formattedHtml, HtmlCompat.FROM_HTML_MODE_LEGACY)
}

@Composable
fun annotatedStringResource(@StringRes id: Int, vararg formatArgs: Any): AnnotatedString {
    val resources = resources()
    val density = LocalDensity.current
    return remember(id, formatArgs) {
        val text = resources.getText(id, *formatArgs)
        spannableStringToAnnotatedString(text, density)
    }
}

@Composable
fun annotatedStringResource(@StringRes id: Int): AnnotatedString {
    val resources = resources()
    val density = LocalDensity.current
    return remember(id) {
        val text = resources.getText(id)
        spannableStringToAnnotatedString(text, density)
    }
}

private fun spannableStringToAnnotatedString(
    text: CharSequence,
    density: Density
): AnnotatedString {
    return if (text is Spanned) {
        with(density) {
            buildAnnotatedString {
                append((text.toString()))
                text.getSpans(0, text.length, Any::class.java).forEach {
                    val start = text.getSpanStart(it)
                    val end = text.getSpanEnd(it)
                    when (it) {
                        is StyleSpan -> when (it.style) {
                            Typeface.NORMAL -> addStyle(
                                SpanStyle(
                                    fontWeight = FontWeight.Normal,
                                    fontStyle = FontStyle.Normal
                                ),
                                start,
                                end
                            )
                            Typeface.BOLD -> addStyle(
                                SpanStyle(
                                    fontWeight = FontWeight.Bold,
                                    fontStyle = FontStyle.Normal
                                ),
                                start,
                                end
                            )
                            Typeface.ITALIC -> addStyle(
                                SpanStyle(
                                    fontWeight = FontWeight.Normal,
                                    fontStyle = FontStyle.Italic
                                ),
                                start,
                                end
                            )
                            Typeface.BOLD_ITALIC -> addStyle(
                                SpanStyle(
                                    fontWeight = FontWeight.Bold,
                                    fontStyle = FontStyle.Italic
                                ),
                                start,
                                end
                            )
                        }
                        is TypefaceSpan -> addStyle(
                            SpanStyle(
                                fontFamily = when (it.family) {
                                    FontFamily.SansSerif.name -> FontFamily.SansSerif
                                    FontFamily.Serif.name -> FontFamily.Serif
                                    FontFamily.Monospace.name -> FontFamily.Monospace
                                    FontFamily.Cursive.name -> FontFamily.Cursive
                                    else -> FontFamily.Default
                                }
                            ),
                            start,
                            end
                        )
                        is BulletSpan -> {
                            Log.d("StringResources", "BulletSpan not supported yet")
                            addStyle(SpanStyle(), start, end)
                        }
                        is AbsoluteSizeSpan -> addStyle(
                            SpanStyle(fontSize = if (it.dip) it.size.dp.toSp() else it.size.toSp()),
                            start,
                            end
                        )
                        is RelativeSizeSpan -> addStyle(
                            SpanStyle(fontSize = it.sizeChange.em),
                            start,
                            end
                        )
                        is StrikethroughSpan -> addStyle(
                            SpanStyle(textDecoration = TextDecoration.LineThrough),
                            start,
                            end
                        )
                        is UnderlineSpan -> addStyle(
                            SpanStyle(textDecoration = TextDecoration.Underline),
                            start,
                            end
                        )
                        is SuperscriptSpan -> addStyle(
                            SpanStyle(baselineShift = BaselineShift.Superscript),
                            start,
                            end
                        )
                        is SubscriptSpan -> addStyle(
                            SpanStyle(baselineShift = BaselineShift.Subscript),
                            start,
                            end
                        )
                        is ForegroundColorSpan -> addStyle(
                            SpanStyle(color = Color(it.foregroundColor)),
                            start,
                            end
                        )
                        else -> addStyle(SpanStyle(), start, end)
                    }
                }
            }
        }
    } else {
        AnnotatedString(text.toString())
    }
}

来源:https://issuetracker.google.com/issues/139320238#comment11
使用这些辅助方法,您可以简单地调用:

Text(annotatedStringResource(R.string.your_string_resource))
rryofs0p

rryofs0p2#

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
        }
    )
}
xe55xuns

xe55xuns3#

要继续使用stringResources(),您可以按照下面的操作。

第一-使用<![CDATA[ … ]]>

<![CDATA[ … ]]>之间包含所有资源HTML字符串,那么在调用stringResources()时就不会丢失HTML定义:

<string name="styled_text"><![CDATA[Sample text with <b>bold styling</b> to test]]></string>

**第二步-创建 “从SpannedAnnotatedString处理器”

首先感谢this awesome answer
然后,重要的是要知道text参数 (来自Text() composable) 也接受AnnotatedString对象,而不仅仅是String
我们可以使用Jetpack buildAnnotatedString()创建一个 “从SpannedAnnotatedString处理器” 算法。
在这种情况下,我会选择 “将算法创建为客户端可组合文件内的扩展private函数” 路径:

private fun Spanned.toAnnotatedString(): AnnotatedString =
    buildAnnotatedString {
        val spanned = this@toAnnotatedString
        append(spanned.toString())

        getSpans(
            0,
            spanned.length,
            Any::class.java
        ).forEach { span ->
            val start = getSpanStart(span)
            val end = getSpanEnd(span)

            when (span) {
                is StyleSpan ->
                    when (span.style) {
                        Typeface.BOLD -> addStyle(
                            SpanStyle(fontWeight = FontWeight.Bold),
                            start,
                            end
                        )

                        Typeface.ITALIC -> addStyle(
                            SpanStyle(fontStyle = FontStyle.Italic),
                            start,
                            end
                        )

                        Typeface.BOLD_ITALIC -> addStyle(
                            SpanStyle(
                                fontWeight = FontWeight.Bold,
                                fontStyle = FontStyle.Italic
                            ),
                            start,
                            end
                        )
                    }

                is ForegroundColorSpan -> addStyle( // For <span style=color:blue> tag.
                    SpanStyle(color = Color.Blue),
                    start,
                    end
                )
            }
        }
    }

第三次-调用HtmlCompat.fromHtml()

在将AnnotatedString发送到Text()组合之前的最后一步,我们需要调用目标String on HtmlCompat.fromHtml()方法以及新的toAnnotatedString()扩展函数:

val textAsAnnotatedString = HtmlCompat.fromHtml(
    stringResource(id = R.string.styled_text),
    HtmlCompat.FROM_HTML_MODE_COMPACT
).toAnnotatedString()

第四-在Text()上显示

然后将其显示在目标Text()组合产品上:

Text(text = textAsAnnotatedString)

注意:您可以在toAnnotatedString()内部添加很多 “样式解释器”

下面的打印 (红色矩形内的所有内容) 来自我的Android项目上的一个可组合SnackBar,使用了与上面相同的策略。

sz81bmfz

sz81bmfz4#

目前,您可以使用AnnotatedString类来显示Text组件中的样式化文本。我给你举个例子:

Text(
    text = buildAnnotatedString {
        withStyle(style = SpanStyle(fontWeight = FontWeight.Thin)) {
            append(stringResource(id = R.string.thin_string))
        }
        withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) {
            append(stringResource(id = R.string.bold_string))
        }
    },
)

根据您指定的样式,您将获得具有红色突出显示样式的文本
https://i.stack.imgur.com/XSMMB.png
更多信息:https://developer.android.com/jetpack/compose/text?hl=nl#multiple-styles

相关问题