Android string.xml resource formatting

If you are using the strings.xml file for your applications string resources (which you should!) then you might have wondered what to do if you need to combine a string and a value.

Take this text for example:

Hi, my name is Ruben and I am 26 years old

String resource formatting

This can easily be solved by using string formatting to insert the values; Ruben and 26.

In you strings.xml file, create a new string resource like this:

<string name="my_name">Hi, my name is %1$s and I am %2$d years old.</string>  

You can then use and format this string resource in you java code like this:

String greetingText = String.format(getResources().getString(R.string.my_name), "Ruben", 26);  

Explanation

As you probably understand, the %1$s is a string placeholder, while the %2$d is an integer placeholder.

The numbers, 1 and 2, are not necessary, but can be used to alter the order of variables. This way, you could use the name parameter several places if you wanted, by creating a string resource like this:

<string name="my_name">Hi, my name is %1$s and I am %2$d years old. Best regards %1$s.</string>  

And use it with the same java code.

You can also insert float variables, specify number of decimals and more.

For more information, check out the Android developer documentation on String resources and the java Formatter helper.

Do you have any other tricks that you use regarding strings or formatting?

comments powered by Disqus