如何使用带格式参数的getQuantityText,以便可以在字符串中使用数量?

问题描述 投票:0回答:1

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

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

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

android string-formatting android-resources
1个回答
3
投票

首先,让我们看看“正常”情况(不起作用的情况)。你有一些复数资源,像这样:

<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 <b> items </ b>”。)这是更新后的代码:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.