How to use plural with String Resources?
For internationalization, Android uses String Resources. How can I take advantage of this feature to use the plural in such a way as to avoid "gambiarras" with multiple if
's?
Example:
<string name="friends_none">Você não tem amigos ainda</string>
<string name="friends_one">Você tem 1 amigo</string>
<string name="friends_plural">Você tem %1$d amigos</string>
if (friends == 1) {
text = getString(R.string.friends_one);
} else if (friends > 1) {
text = getString(R.string.friends_plural, friends);
} else {
text = getString(R.string.friends_none);
}
1 answers
For this specific situation, the android framework provides a feature called "Quantity Strings".
Create a file within the
res/values
directory with any name. Example:res/values/strings_plurais.xml
This file needs to have the root tag
resources
, and inside it you put the tagplurals
.Inside the tag
plurals
put an attributename
to identify it. Example:name="respostas_corretas"
.To create the string, create a tag
item
, and place an attributequantity
. Example:quantity="one"
(for singular) orquantity="other"
(for plural).Then, inside the
item
tag, you put the string to be used in the layout. Example:<item quantity="one">Pontuação: %d ponto.</item>
The file .Final XML should look like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<plurals name="respostas_corretas">
<item quantity="one">Pontuação: %d ponto.</item>
<item quantity="other">Pontuação: %d pontos.</item>
</plurals>
</resources>
Now in Java source code, the string can be obtained this way:
// Chamando numeroRespostasCorretas() para obter o número de respostas corretas
int nRespostasCorretas = numeroRespostasCorretas();
// Obtendo a referência de Resources
Resources resources = getResources();
// Chame o getQuantityString() e passe como paramêtros o ID do plurals criado e passe a variável a ser formatada duas vezes (uma para o formatador e outra para o framework determinar, baseada na variável, se é singular ou plural)
String respostasCorretas = resources.getQuantityString(R.plurals.respostas_corretas, nRespostasCorretas, nRespostasCorretas);
In Kotlin the same way:
val nRespostasCorretas = numeroRespostasCorretas()
val respostasCorretas = resources.getQuantityString(R.plurals.respostas_corretas,
nRespostasCorretas , nRespostasCorretas)
For more information on this topic and about string resources on Android: https://developer.android.com/guide/topics/resources/string-resource?hl=pt-br#top_of_page