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
%[parameter_index$][format_type]
1$
, 2$
, and 3$
. 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 numberWe will create the following formatted string where the gray parts are inserted programmatically.
My sister
Mary
is12
years old.
string.xml
<string name="my_xml_string">My sister %1$s is %2$d years old.</string>
MyActivity.java
String myString = "Mary";
int myInt = 12;
String formatted = getString(R.string.my_xml_string, myString, myInt);
getString
because I was in an Activity. You can use context.getResources().getString(...)
if it is not available.String.format()
will also format a String.1$
and 2$
terms don't need to be used in that order. That is, 2$
can come before 1$
. 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.