2015年6月2日 星期二

[Corona SDK] How to support multi-language (localize your APP)

If we only want to support one language, it will be quite simple for programming.
We can code it  as:
display.newText("hello", 200, 200, native.systemFontBold, 36 )

But, what if we want to support more than two languages?

First, we need to get the information of languages for current settings in user phones.
For Android system, we may use system.getPreference( "locale", "language" ) to get such information.
For iOS, we may use system.getPreference( "ui", "language" ).
However, it will be complicated for Chinese.
There have so-called Simplified Chinese and Traditional Chinese.
To overcome such problem, you can reference the following codes:
language = "en"
isAndroid = false
if(system.getInfo("platformName") == "Android") then
 isAndroid = true
end
if(isAndroid) then
 language = system.getPreference( "locale", "language" )
else
 language = system.getPreference( "ui", "language" )
end

local localeLanguage = system.getPreference( "locale", "language" ):upper()
local localeCountry = system.getPreference( "locale", "country" ):upper()
local uiLanguage = system.getPreference( "ui", "language" ):upper()

if(localeLanguage == "ZH-HANT" or localeLanguage == "ZH_HANT" or uiLanguage == "ZH-HANT" or uiLanguage == "ZH_HANT") then
 language = "zh-Hant"
elseif(localeLanguage == "ZH-HANS" or localeLanguage == "ZH_HANS" or uiLanguage == "ZH-HANS" or uiLanguage == "ZH_HANS") then
 language = "zh-Hans"
elseif(localeLanguage == "中文" or localeLanguage == "ZH" or uiLanguage == "中文" or uiLanguage == "ZH") then
 if(localeCountry == "TW") then
  language = "zh-Hant"
 else
  language = "zh-Hans"
 end
end
After getting the language setting, we need to take care of display problem.
We can add a new multi-language translation file, such as translations.lua as show below:
local translations =
{
    ["hello"] =
    {
        ["en"] = "hello",        
        ["zh-Hant"] = "哈囉",
        ["zh-Hans"] = "哈啰",
        ["fr"] = "Salut",
        ["de"] = "Hallo",

    },      
}

return translations
When we want to display the text, we can code it as:
translations = require("translations")
display.newText( translations["hello"][language], 200, 200, native.systemFontBold, 36 )

沒有留言:

張貼留言