問題描述
我正在創(chuàng)建一個可在所有 3 個移動平臺(Android、iOS a、d Windows Mobile 8)上運(yùn)行的 HTML5 移動應(yīng)用.我正在使用 javascript 進(jìn)行本地化(https://github.com/eligrey/l10n.js/#自述文件).
I'm creating a HTML5 mobile app that runs on all 3 mobile platforms (Android, iOS a,d Windows Mobile 8). I'm using javascript for localization(https://github.com/eligrey/l10n.js/#readme).
該應(yīng)用在瀏覽器上運(yùn)行良好.但是當(dāng)我在移動模擬器上部署它時,本地化不起作用.
The app works fine on the browser. But when I deploy it on the mobile emulator the localization is not working.
我認(rèn)為問題在于 javascript 從瀏覽器獲取語言信息,但在移動設(shè)備中我們使用 PhoneGap 運(yùn)行 HTML5.
I think the issue is that javascript gets language information from the browser, but in the mobile we run the HTML5 using PhoneGap.
有什么方法可以在 PhoeGap 中使用 javascript 啟用本地化.
Is there any way that I can enable localization using javascript in PhoeGap.
推薦答案
我剛剛通過為每個平臺創(chuàng)建一個只返回用戶當(dāng)前語言環(huán)境的自定義 PhoneGap 插件解決了同樣的問題.
I've just solved same kind of problem by creating a custom PhoneGap plugins for each platforms that only returns the user's current locale.
例如,在 Android 上,插件只檢查:
for example, on Android, the plugin only checks:
var message = Locale.getDefault().getLanguage();
然后在 Javascript 方面,當(dāng)您獲得該語言名稱時,例如.en
,您將使用以該語言命名的 JSON 對象.JSON 對象的示例如下所示:
and then in Javascript side, when you've got that language name back, eg. en
, you would use the JSON object that it named after that language. The example of JSON object would look like this:
MyApp.Language = en: {
'Player' : 'Player',
'Players' : 'Players',
'Not Set' : 'Not Set'
},
fi: {
'Player' : 'Pelaaja',
'Players' : 'Pelaajat',
'Not Set' : 'Ei m??ritetty'
}
Android 的插件就這么簡單:
The plugin for Android is simple as this:
JS 文件
window.localizeMe = {
getDefaultLocale: function( callback ) {
cordova.exec(
callback,
function(err) {
callback( 'Error: ' + err.code );
},
"LocalizeMe",
"getDefaultLocale",
[]);
}
}
Java 文件
public class LocalizeMe extends CordovaPlugin {
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if (action.equals("getDefaultLocale")) {
String message = Locale.getDefault().getLanguage();
this.getDefaultLocale(message, callbackContext);
return true;
}
return false;
}
private void getDefaultLocale(String message, CallbackContext callbackContext) {
if (message != null && message.length() > 0) {
callbackContext.success(message);
} else {
callbackContext.error("Expected one non-empty string argument.");
}
}
}
最后,在您的主 JS 文件中,設(shè)置應(yīng)用的語言:
window.localizeMe.getDefaultLocale( function( result ) {
if ( result != null && result.length > 0 ) {
if ( result.toLowerCase().indexOf( 'fi' ) !== -1 ) {
MyApp.Lang = MyApp.Language.fi;
} else {
MyApp.Lang = MyApp.Language.en;
}
}
});
這篇關(guān)于使用 javascript 和 PhoneGap 的 HTML5 移動應(yīng)用本地化的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!