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


3 comments:
Wow, hack of the day for me :-).
Thanks for sharing!
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...)
Thanks for sharing that Romain, I updated the post :)
Post a Comment