Localization of android application. One string re

2019-08-17 02:35发布

问题:

I have such a question: I have an Login/Registration Activity which is by default is using Russian version of strings.xml. So when user is entering application - he sees text in Russian language. But on that activity there is a button to choose another language. When he clicks that button - I open another activity in which he can choose which language to use (English/Spanish/German/etc). When he chooses a language (let's say German). How can I from this point in time, show to the user text which is now should be used from German version of strings.xml? And also - how can I do such a thing: if user's locale is from Russian, Ukraine, Georgia --- then use Russian version of strings.xml, and if user's locale from any other country - user English version of strings.xml? Thanks.

回答1:

I would strongly recommend using lokalise

We have an app with 6 flavours and more than 16 languages. It would be a nightmare, if only this library didn't exist.

They have a tutorial on how to use custom locale: but in short:

    // Create a new Locale object
    Locale locale = new Locale("ru");
    Locale.setDefault(locale);
    // Create a new configuration object
    Configuration config = new Configuration();
    // Set the locale of the new configuration
    config.locale = locale;
    // Update the configuration of the Accplication context
    getResources().updateConfiguration(
        config, 
        getResources().getDisplayMetrics()
    );


回答2:

What you want to do is:

  1. Have a list of language/locale wise content translations in the format of key-value pairs. You can achieve this within the same file or have separate files and name them according to the language-locale combo. I prefer the latter version, easier to maintain.

  2. Next at time of app init, you want to read the phone's current locale with

    Locale current = getResources().getConfiguration().locale;
    

    Map this value to the content files (varies from framework to framework) created above and you have instant localization.