如何将 getQuantityText 与格式参数一起使用,以便可以在字符串中使用数量?

How to use getQuantityText with format argument so quantity can be used in string?

对于简单的字符串,您可以使用 Resources.getQuantityString(int, int, ...) 来传递占位符值。所以复数资源可以在字符串中使用%d,你可以插入实际数量。

我希望在复数中使用字体标记 <b> 等。所以我在看 Resources.getQuantityText(int, int)。不幸的是,您不能传递占位符值。我们在源代码中看到,在带有占位符的 getQuantityString 中,他们使用 String.format.

是否有使用复数字体格式的解决方法?

首先,让我们看一下 "normal" 案例(不起作用的案例)。你有一些复数资源,像这样:

<plurals name="myplural">
    <item quantity="one">only 1 <b>item</b></item>
    <item quantity="other">%1$d <b>items</b></item>
</plurals>

然后您在 Java 中使用它,如下所示:

textView.setText(getResources().getQuantityString(R.plurals.myplural, 2, 2));

如您所见,这只会让您看到没有加粗的“2 项”。

解决方案是将资源中的 <b> 标记转换为使用 html 实体。例如:

<plurals name="myplural">
    <item quantity="one">only 1 &lt;b>item&lt;/b></item>
    <item quantity="other">%1$d &lt;b>items&lt;/b></item>
</plurals>

现在您需要向 Java 代码添加另一个步骤来处理这些 html 实体。 (如果您没有更改 java,您会看到“2 items”。)这是更新后的代码:

String withMarkup = getResources().getQuantityString(R.plurals.myplural, 2, 2);
text.setText(Html.fromHtml(withMarkup));

现在您将成功看到“2 ”。

您可以将字符串包裹在 <![CDATA[]]>:

中,而不是转义 HTML 标签
<plurals name="myplural">
    <item quantity="one"><![CDATA[only 1 <b>item</b>]]></item>
    <item quantity="other"><![CDATA[%1$d <b>items</b>]]></item>
</plurals>

此外,在 Kotlin 中,您可以创建一个扩展函数,以便您可以使用 resources.getQuantityText(R.plurals.myplural, 2, 2):

检索样式复数
fun Resources.getQuantityText(id: Int, quantity: Int, vararg formatArgs: Any): CharSequence {
    val html = getQuantityString(id, quantity, *formatArgs)
    return HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_COMPACT)
}