format statement in a string resource file

CocoNess picture CocoNess · Sep 27, 2012 · Viewed 133.5k times · Source

I have strings defined in the usual strings.xml Resource file like this:

<string name="hello_world"> HELLO</string>

Is it possible to define format strings such as the one below

 result_str = String.format("Amount: %.2f  for %d days ",  var1, var2);

in the strings.xml resource file?

I tried escaping the special characters but its not working.

Answer

LocalPCGuy picture LocalPCGuy · Jan 2, 2014

You do not need to use formatted="false" in your XML. You just need to use fully qualified string format markers - %[POSITION]$[TYPE] (where [POSITION] is the attribute position and [TYPE] is the variable type), rather than the short versions, for example %s or %d.

Quote from Android Docs: String Formatting and Styling:

<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>

In this example, the format string has two arguments: %1$s is a string and %2$d is a decimal integer. You can format the string with arguments from your application like this:

Resources res = getResources();
String text = res.getString(R.string.welcome_messages, username, mailCount);