Search code examples
androidstring-formattingandroid-resources

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


With simple strings you use Resources.getQuantityString(int, int, ...) which lets you pass placeholder values. So the plural resource could use %d in the string, and you could insert the actual quantity.

I wish to use font markups <b> etc inside a plural. So Im looking at Resources.getQuantityText(int, int). Unfortunately, you cannot pass placeholder values. We see in the source code, that in getQuantityString with placeholders, they use String.format.

Is there a workaround to use font formatting in plurals?


Solution

  • First, let's look at the "normal" case (the one that doesn't work). You have some plural resource, like this:

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

    And you use it in Java like this:

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

    As you found, this just causes you to see "2 items" with no bolding.

    The solution is to convert the <b> tags in your resource to use html entities instead. For example:

    <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>
    

    Now you need to add another step to the Java code to handle these html entities. (If you didn't change the java, you'd see "2 <b>items</b>".) Here's the updated code:

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

    Now you will successfully see "2 items".