2015年6月2日 星期二

[Corona SDK] 如何支援多國語言

如果我們只要支援一種語言,
那程式就很簡單,例如:
display.newText("哈囉", 200, 200, native.systemFontBold, 36 )

但,如果想要支援二種以上語言呢?

首先,我們要知道目前使用者手機設定的語言是什麼,
英文,法文,日文等等還比較容易,
但中文有繁體和簡體,加上手機又有Android和iOS二大系統(Window Phone就先跳過吧^^),
Android系統可能要用system.getPreference( "locale", "language" )比較適合,
iOS可能用system.getPreference( "ui", "language" )
將各種可能情形總結,可參考以下的範例:
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
取得語言設定後,再來就是顯示的問題,
我們可以新增一個多國語言的翻譯字串檔案,
例如translations.lua,裡面的內容如下:
local translations =
{
    ["hello"] =
    {
        ["en"] = "hello",        
        ["zh-Hant"] = "哈囉",
        ["zh-Hans"] = "哈啰",
        ["fr"] = "Salut",
        ["de"] = "Hallo",

    },      
}

return translations
顯示字串時,我們可以改寫如下:
translations = require("translations")
display.newText( translations["hello"][language], 200, 200, native.systemFontBold, 36 )

沒有留言:

張貼留言