How to use plural with String Resources?

Asked

Viewed 81 times

0

For internationalization, Android uses String Resources. How can I use this feature to use plural to avoid multiple "gambiarras" 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 answer

5


For this specific situation, the android framework provides a feature called "Quantity Strings" (Quantity strings).

  1. Create a file inside the directory res/values with any name. Example: res/values/strings_plurais.xml

  2. This file needs to have the root tag resources, and within it you tag plurals.

  3. Inside the tag plurals place an attribute name to identify it. Example: name="respostas_corretas".

  4. To create the string, create a tag item, and place an attribute quantity. Example: quantity="one" (for single) or quantity="other" (plural).

  5. 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.