androidinternationalizationtranslationplural

Android Plural Strings with multiple Parameters


In Android strings, you can define plurals to handle translations depending on the actual number supplied to the string as described here. Strings also allow for specifying multiple positional parameters similar to what sprintf does in many languages.

However, consider the following string:

<resources>
    <string name="remaining">%1$d hours and %2$d minutes remaining.</string>
</resources>

It contains two numbers, how would I transform this to a plural in Android? All examples always work with a single parameter only. Is this even possible?


Solution

  • getQuantityString has an overloaded version that takes a String id, the quantity and a varargs of object that you could use to format your string. Even though seems possible to use plural, it sounds strange to me for time. You could use the helper methods contained in DateUtil, which are already localized and take care of singular/plural and then complete your string with the results of these helper methods. E.g. getRelativeTimeSpanString

    <plurals name="number_of_emails">
        <item quantity="one">%d email</item>
        <item quantity="other">%d emails</item>
    </plurals>
    
    <plurals name="number_of_messages">
        <item quantity="one">%d message</item>
        <item quantity="other">%d messages</item>
    </plurals>
    

    and then you can use getQuantityString to retrieve the two pieces and combine it in one.