How to format string in Android

If we want to concatenate multiple strings or reference one string from another string in strings.xml we can use following snippet

<string name="hello">Hello</string>
<string name="world">@string/hello world!</string>>

Output is Hello world!.

If you need to format your strings using String.format(String, Object...), then you can do so by putting your format arguments in the string resource. For example, with the following resource:

<string name="movie_info">%1$s! released in %2$d.</string>

Somewhere in code

Resources res = getResources();
String text = String.format(res.getString(R.string.movie_info), movie.title, movie.year);
comments powered by Disqus