Saturday, October 31, 2009

Variable in Android's strings.xml

Today I was wondering how to create a variable in strings.xml, a file used in Android application development.

It is actually very simple. :)

First define a string in the strings.xml file (usually res/values/strings.xml).

<string name="unread_messages">You have %d unread messages</string>

This string has a variable %d that will be replaced in the next step.

In the Java code the string is fetched with the getString method and the variable is replaced with the right content using Java's String formatter.

String message = String.format(getString(R.string.unread_messages), 10);

The output will be You have 10 unread messages... :)

Update: As Romain Guy points out in the comments it is even simpler, documented here:

String message = getString(R.string.unread_messages, 10);