Appcelerator Changing Language Programmatically

18. June 2014 Blog 0

Appcelerator follows the Android standard convention for internationalization. Basically you setup a i18n folder and then create folders named with the ISO 639-1 code for the language and put a strings.xml file in each. So basically you end up with a folder structure like this:

i18n
...en
......strings.xml
...fr
......strings.xml
...zh
......strings.xml

Only problem with this is you have no control as the programmer for what language is used when you use the built in L() function. So instead of doing it this way I came up with a different way. I use a single strings.xml file just for en then inside that file I construct the strings like this:

<?xml version="1.0" encoding="UTF-8"?>
<resources>
<string name="en_home">Home</string>
<string name="fr_home">Maison</string>
<string name="zh_home">家</string>
</resources>

Then I just have a global property that can be set, so by default I make it English. So this could be in your index controller.

Alloy.Globals.currentLanguage = ‘en’;

Then anytime I need to use the translate function L() I simply do it like this:

L(Alloy.Globals.currentLanguage + ‘_home’);

That way if the language gets changed it pulls the correct language.

If you want to take it a step farther you can even use different xml files for each language and then create a program to parse all of them into a single .xml file. I did this with a simple php script.

Hopefully this will help other Appcelerator developers out.


Leave a Reply

Your email address will not be published.