07 September 2010

Quick string resource formatting

Sooner or later, you would want to display a message to your user with dynamic content. This may be the number of results, the user's name, etc.

Luckily for us, Android provides a convenience method that we can use for such purposes.
public final String getString (int resId, Object... formatArgs)
This means that we can define a string in our strings.xml file with format specifiers supported by Java's formatter class. For example, if I have such a string:
<string name="formatted_string">Hello, %s! You have %d messages.</string>
I can get this string, apply the formatting, and then set it into a TextView without additional processing on my part.
TextView string = (TextView) findViewById(R.id.form_string);
string.setText(getString(R.string.formatted_string, "Zarah", 4));
And I will have this:
Nifty and easy!

Of course, this is a simple example. But I hope you get the drift. Do read the Formatter's documentation to see all possible formats you can use.