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

and*_*guy 6 android string-formatting android-resources

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

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

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

Ben*_* P. 5

首先,让我们看看“正常”情况(不起作用的情况)。您有一些复数资源,如下所示:

<plurals name="myplural">
    <item quantity="one">only 1 <b>item</b></item>
    <item quantity="other">%1$d <b>items</b></item>
</plurals>
Run Code Online (Sandbox Code Playgroud)

你可以像这样在 Java 中使用它:

textView.setText(getResources().getQuantityString(R.plurals.myplural, 2, 2));
Run Code Online (Sandbox Code Playgroud)

正如您所发现的,这只会导致您看到没有粗体的“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>
Run Code Online (Sandbox Code Playgroud)

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

String withMarkup = getResources().getQuantityString(R.plurals.myplural, 2, 2);
text.setText(Html.fromHtml(withMarkup));
Run Code Online (Sandbox Code Playgroud)

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