Android strings.xml — things to remember
This article is about such trivial android thing as — strings.xml
Do not reuse
Do not reuse strings for different screens.
1. Imagine you have a loading dialog on Sign In and Sign Up screens. Both have loading dialog and you decided to use the same string —R.string.loading.
Later if you decide to use different one, you will have to create two new strings and do modification in java code. If you used two strings from the beginning you would have to modify only strings.xml file.
2. You never know which language your application may support. In one language — you will be able to use the same word for different context, but in another — you will have to use different words for different context.
Note that English version of strings.xml uses the same word — “Yes” for both R.string.download_file_yes and R.string.terms_of_use_yes strings.
But Ukrainian version of strings.xml uses two different words — “Гаразд” for R.string.download_file_yes and “Так” for R.string.terms_of_use_yes.
Separate strings which belong to the same screen via prefix and comment
- Adding screen name prefix to every string helps to immediately recognize screen which current string belong to.
- Clean strings.xml file helps to easily maintain and translate strings to different languages — screen after screen.
Creating separate strings.xml file per screen
If you want you can create strings.xml file per screen — settings-strings.xml, profile-strings.xml. But usually apps have 10–20 screens. So having 10–20 strings.xml files in every language folder, in my opinion, would bring huge mess.
Use Resources#getString(int id, Object… formatArgs) to format strings
Never do string concatenation via + operator, because in other languages words order may vary.
Correct way is to use Resources#getString(int id, Object… formatArgs).
Use Resources#getQuantityString (int id, int quantity) for quantity strings
Never resolve plurals in your java code, because different languages have different rules for grammatical agreement with quantity.
Correct way is to use Resources#getQuantityString (int id, int quantity).
Use html text to highlight static words
If you want to change color of some words in TextView — ForegroundColorSpan is not always a best choice, because highlighting is done via indexes and it’s not safe in multi language app. Better to use html font color tags inside your strings.xml file.
Imagine you have text “Discover and play games.” and you want to highlight “Discover” word and “play” word with blue color.