Are parameters in strings.xml possible?


In my Android app I'am going to implement my strings with internationalization. I have a problem with the grammar and the way sentences build in different languages.

For example:

"5 minutes ago" - English

"vor 5 Minuten" - German

Can I do something like the following in strings.xml?

<string name="timeFormat">{0} minutes ago</string>

And then some magic like

getString(, dynamicTimeValue)

This behaviour would solve the other problem with different word orders as well.

12/29/2018 8:32:37 AM

Accepted Answer

Yes, just format your strings in the standard String.format() way.

See the method Context.getString(int, Object...) and the Android or Java Formatter documentation.

In your case, the string definition would be:

<string name="timeFormat">%1$d minutes ago</string>
3/7/2010 7:46:22 PM

If you need two variables in the XML you can use:

%1$d text... %2$d or %1$s text... %2$s for string variables.



<string name="notyet">Website %1$s isn\'t yet available, I\'m working on it, please wait %2$s more days</string>

String site = "mywebsite";
String days = "11";

//Toast example
String notyet = getString(R.string.notyet, site, days);
Toast.makeText(getApplicationContext(), notyet, Toast.LENGTH_LONG).show();

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow