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
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
in res/values/string.xml
in java code
Supplemental Answer
When I first saw
%1$s
and%2$d
in the accepted answer, it made no sense. Here is a little more explanation.They are called format specifiers. In the xml string they are in the form of
1$
,2$
, and3$
. The order you place them in the resource string doesn't matter, only the order that you supply the parameters.format type: There are a lot of ways that you can format things (see the documentation). Here are some common ones:
s
stringd
decimal integerf
floating point numberExample
We will create the following formatted string where the gray parts are inserted programmatically.
string.xml
MyActivity.java
Notes
getString
because I was in an Activity. You can usecontext.getResources().getString(...)
if it is not available.String.format()
will also format a String.1$
and2$
terms don't need to be used in that order. That is,2$
can come before1$
. This is useful when internationalizing an app for languages that use a different word order.%1$s
multiple times in the xml if you want to repeat it.%%
to get the actual%
character.Was looking for the same and finally found the following very simple solution. Best: it works out of the box.
1. alter your string ressource:
2. use string substitution:
c.getString(R.string.welcome_messages,name,count);
where c is the Context, name is a string variable and count your int variable
You'll need to include
in your res/strings.xml. Works for me. :)
Kotlin version of the accepted answer...
When you want to use a parameter from the actual strings.xml file without using any Java code:
This does not work across resource files, i.e. variables must be copied into each XML file that needs them.
Formatting and Styling
Yes, see the following from String Resources: Formatting and Styling
Basic Usage
Note that
getString
has an overload that uses the string as a format string:Plurals
If you need to handle plurals, use this:
The first
mailCount
param is used to decide which format to use (single or plural), the other params are your substitutions:See String Resources: Plurals for more details.