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:
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 :)
Thanks, exactly what I was looking for, especially Romain Guy's way.
This was very helpful, even 2 years after the original post. Thanks a lot!
Why show the long, confusing way first? Or at all
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.
Post a Comment