Set Locale programmatically

后端 未结 14 1462
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:26

    Valid for API16 to API28 Just place this method some where:

    Context newContext = context;
    
    Locale locale = new Locale(languageCode);
    Locale.setDefault(locale);
    
    Resources resources = context.getResources();
    Configuration config = new Configuration(resources.getConfiguration());
    
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        config.setLocale(locale);
        newContext = context.createConfigurationContext(config);
    } else {
        config.locale = locale;
        resources.updateConfiguration(config, resources.getDisplayMetrics());
    }
    
    return newContext;
    

    Insert this code in all your activitys using:

        @Override
        protected void attachBaseContext(Context base) {
            super.attachBaseContext(localeUpdateResources(base, "<-- language code -->"));
        }
    

    or call localeUpdateResources on fragments, adapters, etc. where you need the new context.

    Credits: Yaroslav Berezanskyi

提交回复
热议问题