Search code examples
androidstringlocale

How to add a test condition on Locale


I am trying to translate my app in english, french, spanish and hungarian.
I want to translate the string "1 out of 2" dynamically. So, the "out of" part in a string resource and use code to append and prepend the numbers.
It goes fine for french (1 sur 2) and spanish (1 de 2). However, for hungarian language, it should be "1 a 2-ből".
Notice the suffix "-ből".
So, I want to prepend this suffix only for hungarian locale (using test condition).

My code is as follows :

// Example : "1 out of 2"
textToRead = item.itemIndex() + getContext().getResources().getString(R.string.index_over_size_separator) + item.numberOfSiblings();

index_over_size_separator is the "out of" string resource.
Now, suppose hungarian_suffix is the hungarian suffix I want to append (if system language is hungarian), how can I achieve this in a simple manner ?


Solution

  • You can use Ressources strings like that to display dynamic values:

    <!-- french -->
    <string name="index">%d sur %d</string>
    
    <!-- english-->
    <string name="index">%d out of %d</string>
    
    <!-- spanish -->
    <string name="index">%d de %d</string>
    
    <!-- hungarian -->
    <string name="index">%d a %d-ből</string>
    

    You can then fill the %d values in your getString()

    textToRead = getContext().getResources().getString(R.string.index_over_size_separator, item.itemIndex(), item.numberOfSiblings());
    

    See this for more informations