HTML5 Mobile app localization using javascript and PhoneGap

前端 未结 3 519
粉色の甜心
粉色の甜心 2021-01-01 03:21

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/l

3条回答
  •  抹茶落季
    2021-01-01 03:44

    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.

    for example, on Android, the plugin only checks:

    var message = Locale.getDefault().getLanguage();

    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'
    }
    

    The plugin for Android is simple as this:

    JS file

    window.localizeMe = {
        getDefaultLocale: function( callback ) {
            cordova.exec(
                callback,
                function(err) {
                    callback( 'Error: ' + err.code );
                },
                "LocalizeMe",
                "getDefaultLocale",
                []);
        }
    }
    

    Java file

    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.");
            }
        }
    
    }
    

    And finally, in your main JS file, you set your app's language:

    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;
            }
        }
    });
    

提交回复
热议问题