Plurals resource for String in Android Android 12.07.2019

Externalizing your strings helps maintain consistency within your application and makes it much easier to internationalize them.

String resources are specified with the string tag, as shown in the following XML snippet:

<string name="stop_message">Stop.</string>

Android supports simple text styling, so you can use the HTML tags <b>, <i>, and <u> to apply bold, italics, or underlining, respectively, to parts of your text strings, as shown in the following example:

<string name="stop_message"><b>Stop.</b></string>

You can also define alternative plural forms for your strings. This enables you to define different strings based on the number of items you refer to. For example, in English you would refer to "one Android" but "seven Androids".

By creating a plurals resource, you can specify an alternative string for any of zero, one, multiple, few, many, or other quantities. In English the singular is a special case, whereas some languages require finer detail and in others the singular is never used:

<plurals name="unicorn_count">
    <item quantity="one">One unicorn</item> 
    <item quantity="other">%d unicorns</item>
</plurals>

To access the correct plural in code, use the getQuantityString method on your application’s Resources object, passing in the resource ID of the plural resource, and specifying the number of objects you want to describe:

val unicornCount = 5
val unicornStr = resources.getQuantityString(
    R.plurals.unicorn_count, unicornCount, unicornCount
)
textView.text = unicornStr

Note that in this example the object count is passed in twice - once to return the correct plural string, and again as an input parameter to complete the sentence.