For this specific situation, the android framework provides a feature called "Quantity Strings" (Quantity strings).
Create a file inside the directory res/values
with any name. Example: res/values/strings_plurais.xml
This file needs to have the root tag resources
, and within it you tag plurals
.
Inside the tag plurals
place an attribute name
to identify it. Example: name="respostas_corretas"
.
To create the string, create a tag item
, and place an attribute quantity
. Example: quantity="one"
(for single) or quantity="other"
(plural).
Then inside the tag item
, you place the string to be used in the layout. Example:
<item quantity="one">Pontuação: %d ponto.</item>
The final . XML file 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 in the same way:
val nRespostasCorretas = numeroRespostasCorretas()
val respostasCorretas = resources.getQuantityString(R.plurals.respostas_corretas,
nRespostasCorretas , nRespostasCorretas)
For more information about this topic and string features on Android:
https://developer.android.com/guide/topics/resources/string-resource?hl=pt-br#top_of_page