How to do an app with truly multilingual strings?

前端 未结 4 2074
渐次进展
渐次进展 2021-02-03 14:34

what should be the best approach to make strings for different languages? I have this problem, I am trying to display strings such as \'month\', \'months\', \'year\', \'years\'.

4条回答
  •  时光说笑
    2021-02-03 14:55

    Thanks to the answers I have got, I am writing 2 Android based solutions. The first one I used was having plurals. At first glance checking the Plurals docs/examples, you could think that there is a quantity="few" (for 2-4 plurals) which checking at the sources only works for locale 'cs'. For the rest of locales, only "one" and "other" are working. So in your strings.xml files:

    
        1 year
        %d years
    
    

    So for polish I would have:

    
        1 rok
        %d lat
    
    

    Then I would have on my code:

    int n = getYears(...);
    if (Locale.getDefault().getLanguage().equalsIgnoreCase("pl") && n >= 2 && n <= 4) {
       return getString(R.string.years_pl, n);
    } else {
       return getResources().getQuantityString(R.plurals.years, n, n);
    }
    

    And in my strings.xml file for the polish locale I would add the missing string:

    %d lata
    

    My second solution has the plurals element for english, spanish, and other languages that don't have too many plural changes. Then for the rest of the languages that have this kind of changes I would use ChoiceFormat. So in my code:

    ...
    private static final int LANG_PL = 0;
    // add more languages here if needed
    ...
    String formats[] = {
    "{0,number} {0,choice,1#" + getString(R.string.year_1) + "|2#" + getString(R.string.years_2_4) +  "|4<" + getString(R.string.years_lots) +"}", // polish
    // more to come
    };
    ...
    // Here I would add more for certain languages
        if (Locale.getDefault().getLanguage().equalsIgnoreCase("pl")) {
           return MessageFormat.format(formats[LANG_PL], n);
        } else {
           return getResources().getQuantityString(R.plurals.years, n, n);
        }
    

    I don't know if these ways are the best way, but for the moment, or until Google makes something better, this works for me.

提交回复
热议问题