Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a string for different language with different arguments in Android?

Tags:

android

I have two string resources. The first one in main\values is in English and doesn't have a string argument:

<string name="example">Have a good day!</string>

But in French, under values-fr, we have a different phrase with one argument, like so:

<string name="example">Bonne journée M. %1$s!</string>

How should I use the resource string formatter? This works, but it doesn't seem right (and it generates a lint warning):

textView.setText(getString(R.string.example, name));

The lint warning is "StringFormatInvalid" and the description is "Format string 'example' is not a valid format string so it should not be passed to String.format"

like image 568
Thierry-Dimitri Roy Avatar asked Oct 18 '22 17:10

Thierry-Dimitri Roy


1 Answers

There is nothing wrong with your approach. The formatter works perfectly even if there are too many arguments. The leftover arguments just get dropped.

Lint warnings are there to indicate possible unintended errors in the code. But if you know what you are doing you just may suppress the warning by adding the @SuppressLint("StringFormatMatches") annotation to the enclosing method or class.

like image 61
Floern Avatar answered Oct 21 '22 07:10

Floern