Plurals in Android:
Plurals are a type of resource, we use it very often to deal with plurality of Strings, what does plurality of Strings means ?
well suppose you are counting books and you want to print out the result, you will have to write at least 2 Strings like:
<resources>
<string name="zero">there is no books !</string>
<string name="one">there is one book</string>
<string name="moreThanOne">there are %d books</string>
</resources>
and then you will add some logic to your code
if (booksCount ==0)
{
result= getString(R.string.zero);
}
else if (booksCount ==1)
{
result= getString(R.string.one);
}
else if (booksCount >1)
{
result= getString(R.string.moreThanOne, booksCount);
}
textView.setText(result);
and that is not good to keep languages logic inside your code, imagine you have many internationalized text and every languages have its formatting rules !
here comes plurals to solve this problem:
we are going to use “Plurals” tag rather than “String” tag
<resources>
<plurals name="numberOfBooks">
<item quantity="one">%d book!</item>
<item quantity= "other">%d books!</item>
</plurals>
</resources>
note that each language have limited quantity values based on grammar of each language, for English there are only two values of quantity “one” and “other”, “zero” is not allowed in english
we are going to use getQuantityString method
int booksCount= 20;
String result = getResources().getQuantityString(R.plurals.numberOfBooks, booksCount,booksCount);
textView.setText(result);
result should be “20 books!”
another example shows the power of plurals with internationalized text “Arabic” :
<resources>
<plurals name="numberOfBooks">
<item quantity="zero">لا يوجد كتب !</item>
<item quantity="one">يوجد كتاب واحد !</item>
<item quantity="two">يوجد كتابين !</item>
<item quantity="few">يوجد %d كتب</item>
<item quantity="many">يوجد %d كتاباً!</item>
<item quantity= "other">يوجد %d كتاب!</item>
</plurals>
</resources>
you notice here there are many values in arabic such as ” zero”, “two”,”few”,”many” this is because of arabic grammar, it follows these rules
zero → n is 0;
one → n is 1;
two → n is 2;
few → n mod 100 in 3..10;
many → n mod 100 in 11..99;
other → everything else
and for full list of Languages Plurals Rules click here
for Android Plurals Documentation click here
Happy Coding!