使用 javascript 和 PhoneGap 的 HTML5 移动应用本地化
我正在创建一个可在所有 3 个移动平台(Android、iOS a、d Windows Mobile 8)上运行的 HTML5 移动应用.我正在使用 javascript 进行本地化(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).
该应用在浏览器上运行良好.但是当我在移动模拟器上部署它时,本地化不起作用.
The app works fine on the browser. But when I deploy it on the mobile emulator the localization is not working.
我认为问题在于 javascript 从浏览器获取语言信息,但在移动设备中我们使用 PhoneGap 运行 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.
推荐答案
我刚刚通过为每个平台创建一个只返回用户当前语言环境的自定义 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 方面,当您获得该语言名称时,例如.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 文件中,设置应用的语言:
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;
}
}
});
相关文章