Android String formatting in strings.xml


Defining Strings in the strings.xml file also allows for string formatting. The only caveat is that the String will need to be dealt with in code like below, versus simply attaching it to a layout.

<string name="welcome_trainer">Hello Pokémon Trainer, %1$s! You have caught %2$d Pokémon.</string>
String welcomePokemonTrainerText = getString(R.string.welcome_trainer, tranerName, pokemonCount);

In above example,
'%' separates from normal characters,
'1' denotes first parameter,
'$' is used as separator between parameter number and type,
's' denotes string type ('d' is used for integer)

Note that getString() is a method of Context or Resources, i.e. you can use it directly within an Activity instance, or else you may use getActivity().getString() or getContext().getString() respectively.