Android Resources String formatting in strings.xml

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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,
%1$s
'%' 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.



Got any Android Question?