Set Locale programmatically

后端 未结 14 1446
Happy的楠姐
Happy的楠姐 2020-11-22 05:55

My app supports 3 (soon 4) languages. Since several locales are quite similar I\'d like to give the user the option to change locale in my application, for instance an Itali

14条回答
  •  情深已故
    2020-11-22 06:31

    I had a problem with setting locale programmatically with devices that has Android OS N and higher. For me the solution was writing this code in my base activity:

    (if you don't have a base activity then you should make these changes in all of your activities)

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(updateBaseContextLocale(base));
    }
    
    private Context updateBaseContextLocale(Context context) {
        String language = SharedPref.getInstance().getSavedLanguage();
        Locale locale = new Locale(language);
        Locale.setDefault(locale);
    
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return updateResourcesLocale(context, locale);
        }
    
        return updateResourcesLocaleLegacy(context, locale);
    }
    
    @TargetApi(Build.VERSION_CODES.N)
    private Context updateResourcesLocale(Context context, Locale locale) {
        Configuration configuration = context.getResources().getConfiguration();
        configuration.setLocale(locale);
        return context.createConfigurationContext(configuration);
    }
    
    @SuppressWarnings("deprecation")
    private Context updateResourcesLocaleLegacy(Context context, Locale locale) {
        Resources resources = context.getResources();
        Configuration configuration = resources.getConfiguration();
        configuration.locale = locale;
        resources.updateConfiguration(configuration, resources.getDisplayMetrics());
        return context;
    }
    

    note that here it is not enough to call

    createConfigurationContext(configuration)
    

    you also need to get the context that this method returns and then to set this context in the attachBaseContext method.

提交回复
热议问题