Android multilanguage support: string formatting issue due to different placeholder counts

Viewed 273

I'm making a french Android app and I'm trying to support English.

I use "placeholders" to format my strings, so I can adapt them to male and female users. For example, this string in my strings.xml file:

<string name="encouraging_comment">
    Les %1$s sont compliqué%2$ss...
</string>

will become "Les hommes sont compliqués" ("Men are complicated") or "Les femmes sont compliquées" ("Women are complicated").

And there lies my problem. The string translation, as follows...

<string name="encouraging_comment">
    %1$s are complicated...
</string>

...needs only one placeholder, when the french equivalent needs two.

How can I manage this issue ? Thanks in advance.

3 Answers

AFAIK, you can do this by adding check in your code like

String result;
if ( Locale.getDefault().getLanguage().equals("en")){  // examples "en", "fr", "sp"
      result= getString(R.string.encouraging_comment, myString);
    }
    else{
      result= getString(R.string.encouraging_comment, myString, myStringTwo);
    }
textView.setText(result);

Hope this helps you :)

One way to do this is create a string locale in your strings.xml

for English Strings.xml

<string name="locale">En</string>

for French Strings.xml

<string name="locale">Fr</string>  

Then while setting string

 switch (getString(R.string.locale)) {
            case "Fr":
                //set your string for French
                break;
            case "En":
                //set your string for English 
                break;
        }

Just omit the second placeholder from the English template string and use an empty string for the second argument (or any other string, it doesn't matter, the value will be ignored) when you render the string:

XML:

<string name="encouraging_comment">
    %1$s are complicated...
</string>

Java:

getString(R.string.encouraging_comment, "women", "");
getString(R.string.encouraging_comment, "men", "");

This works because it's not an error if there are more arguments than placeholders, only if there are fewer arguments than placeholders.

I'm assuming that you'll have some kind of table or mapping where you look up the placeholder values based on language and gender. In pseudo-code:

(French,  Female) -> ("femmes", "e")
(French,  Male)   -> ("hommes", "" )
(English, Female) -> ("women",  "" )
(English, Male)   -> ("men",    "" )
Related