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);

7 comments:

paddyzab said...

Wow, hack of the day for me :-).

Thanks for sharing!

Romain Guy said...

It's actually easier than that. Just use getString(R.string.theString, 462, argument2, etc);

See http://d.android.com/reference/android/content/Context.html#getString(int,%20java.lang.Object...)

Unknown said...

Thanks for sharing that Romain, I updated the post :)

Artem Russakovskii said...

Thanks, exactly what I was looking for, especially Romain Guy's way.

Unknown said...

This was very helpful, even 2 years after the original post. Thanks a lot!

Anonymous said...

Why show the long, confusing way first? Or at all

S. Morgan Biggs said...

What version do you need for the "easy" way? I'm programming for 1.5, and the compiler WILL NOT allow it.

The "long way" works fine.