Is it possible to have placeholders in string values in string.xml
that can be assigned values at run time?
Example:
some string PLACEHOLDER1 some more string
Another reason for storing strings in xml is for localization. You can store different files for each different Locale or language, and Android will grab the correct file for the phone's selected Locale or language.
Note: A string is a simple resource that is referenced using the value provided in the name attribute (not the name of the XML file). So, you can combine string resources with other simple resources in the one XML file, under one <resources> element. file location: res/values/filename.xml.
Yes, see the following from String Resources: Formatting and Styling
If you need to format your strings using
String.format(String, Object...)
, then you can do so by putting your format arguments in the string resource. For example, with the following resource:<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
In this example, the format string has two arguments:
%1$s
is a string and%2$d
is a decimal number. You can format the string with arguments from your application like this:Resources res = getResources(); String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);
Note that getString
has an overload that uses the string as a format string:
String text = res.getString(R.string.welcome_messages, username, mailCount);
If you need to handle plurals, use this:
<plurals name="welcome_messages"> <item quantity="one">Hello, %1$s! You have a new message.</item> <item quantity="other">Hello, %1$s! You have %2$d new messages.</item> </plurals>
The first mailCount
param is used to decide which format to use (single or plural), the other params are your substitutions:
Resources res = getResources(); String text = res.getQuantityString(R.plurals.welcome_messages, mailCount, username, mailCount);
See String Resources: Plurals for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With