Resource files are one of the major strength in Android SDK that allows you to separate presentation from application logic. String resources in particular helps to effectively manage multi-lingual applications with ease.
In this tutorial, I will be showing how to use formatted string resources in Android. In addition to discussing the benefits of using formatted strings, the tutorial will show (a) how to define formatted string resources in xml, and (b) how to problematically use them when developing applications.
Why format strings?
Formatted strings offer many benefits for an application developer. These include:
- Improved maintainability: The format is written once (either in code or in a properties/resource file) and can be used in multiple places in code. Consequently, you only need to change a single place if you are changing the format of the string. You only need to update where the format is being used only if the position/type/number of the arguments are changed. This is specially handy when dealing with multiple locales. This is because (a) you have only one string literal to change (i.e. the format), and (b) can specify the ordering of the arguments (as part of the format) based on the language being used. As a result, your code itself is not tightly coupled with locales, and you can leverage the framework (in this case Android SDK) to take care of locale changes for you!
- Reusability: your formatted string can be reused by multiple classes, and consequently makes maintaining code much easier!
- Readability – This is somewhat subjective, but I find most formatted strings to be easy to read than a bunch of string concatanations
How to specify and use formatted strings in Android?
- Specify the formatted string in the resource file (e.g.
strings.xml). This particular format string takes in two arguments, both of which are strings.
- In the Java code (e.g. within an
123456String personToBeamUp = "Bob"; // or from user inputString operator = "Scott";// get the format '%1$s! Beam %2$s up!!' from resource fileString format = getResources().getString(R.string.fmtBeamMeUp);String value = String.format(format, operator, personToBeamUp);// value will be "Scott! Beam Bob up!!"
Check out the Java documentation if you want to know more about Java string formatting.
Please feel free to ask me any questions you might have!