Oct 13, 2012

Setting the locale of your application from code

Hi folks,

The built-in localization system of the Android is pretty straightforward, but sometimes you will need to change the locale of your app without changing the global locale settings on the device. If you really need this, the process is easy. Just create an Application subclass and load a locale code from somewhere (from the app preferences, from the device location, etc.):
public class LocalizedApplication extends Application {

    @Override
    public void onCreate() {
        initLocalization();
        super.onCreate();
    }
    
    private void initLocalization() {
        // Load a locale with specifying an IETF language
        // code, the short one:
        String languageToLoad = "en";
        // or the country-specific:
        String languageToLoad = "en_US";
        Locale locale = new Locale(languageToLoad);
        // or load a Locale directly:
        Locale locale = Locale.US;
        Locale.setDefault(locale);
        Configuration config = new Configuration();
        config.locale = locale;
        getBaseContext().getResources()
            .updateConfiguration(config, getBaseContext().
                getResources().getDisplayMetrics());
    }
}
You have to specify in the manifest xml that you using your own application subclass:
<application
        android:debuggable="true"
        android:icon="@drawable/launcher"
        android:label="@string/app_name"
        android:name=".base.LocalizedApplication">

        <!-- other manifest stuff goes here -->

</application>


A word of advice: this should be considered only as a final solution, if your app logic (or your client) really needs to manage the locale settings by itself. While this is a perfectly working and correct solution, changing the locale in this way goes against the common Android practice, and it can confuse the users of your  application.

No comments:

Post a Comment