Thursday, 21 August 2014

Localized getString() with parameters


getString

We all know the getString() method which is available in the Resources class and in the Context class. However, did you know that there is also a second version of that method that accepts parameters that will be merged into a format string? You can find the Android documentation here.

Simple example

Here is an example of this version of getString():

In your xml file:
 <string name="hello_person">Hello %1$s, how are you?</string>  

In your Java file:
 String userName = getUserName();  
 String hello = getResources().getString(R.string.hello_person, userName);  

This simplifies your code a lot. And it really is but a convenience at you can see in the source Android code:

 public String getString(int id, Object... formatArgs) throws NotFoundException {  
   String raw = getString(id);  
   return String.format(mConfiguration.locale, raw, formatArgs);  
 }  

Multipe placeholders example

You can also have more than one placeholder in your original string, and you can use more than one type:

In your xml file:

 <string name="hello_person_age">Hello %1$s, you are %2$d years old</string>   

In your Jave file:

 String userName = getUserName();  
 int age = getAge();  
 String hello = getResources().getString(R.string.hello_person_age, userName, age);   

Context class

And how about the version in the Context class?  It just delegates to the method in the Resources class:

 public final String getString(int resId, Object... formatArgs) {  
   return getResources().getString(resId, formatArgs);  
 }  

Thanks to +Wolfram Rittmeyer for tuning me into this version of getString()!