Set Locale programmatically

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

    Add a helper class with the following method:

    public class LanguageHelper {
        public static final void setAppLocale(String language, Activity activity) {
    
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                Resources resources = activity.getResources();
                Configuration configuration = resources.getConfiguration();
                configuration.setLocale(new Locale(language));
                activity.getApplicationContext().createConfigurationContext(configuration);
            } else {
                Locale locale = new Locale(language);
                Locale.setDefault(locale);
                Configuration config = activity.getResources().getConfiguration();
                config.locale = locale;
                activity.getResources().updateConfiguration(config,
                        activity.getResources().getDisplayMetrics());
            }
    
        }
    }
    

    And call it in your startup activity, like MainActivity.java:

    public void onCreate(Bundle savedInstanceState) {
        ...
        LanguageHelper.setAppLocale("fa", this);
        ...
    }
    

提交回复
热议问题