Change app language programmatically in Android

前端 未结 30 2978
面向向阳花
面向向阳花 2020-11-21 04:34

Is it possible to change the language of an app programmatically while still using Android resources?

If not, is it possible to request a resource in an specific lan

30条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-21 05:23

    If you want to mantain the language changed over all your app you have to do two things.

    First, create a base Activity and make all your activities extend from this:

    public class BaseActivity extends AppCompatActivity {
    
        private Locale mCurrentLocale;
    
        @Override
        protected void onStart() {
            super.onStart();
    
            mCurrentLocale = getResources().getConfiguration().locale;
        }
    
        @Override
        protected void onRestart() {
            super.onRestart();
            Locale locale = getLocale(this);
    
            if (!locale.equals(mCurrentLocale)) {
    
                mCurrentLocale = locale;
                recreate();
            }
        }
    
        public static Locale getLocale(Context context){
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    
            String lang = sharedPreferences.getString("language", "en");
            switch (lang) {
                case "English":
                    lang = "en";
                    break;
                case "Spanish":
                    lang = "es";
                    break;
            }
            return new Locale(lang);
        }
    }
    

    Note that I save the new language in a sharedPreference.

    Second, create an extension of Application like this:

        public class App extends Application {
    
        @Override
        public void onCreate() {
            super.onCreate();
            setLocale();
        }
    
        @Override
        public void onConfigurationChanged(Configuration newConfig) {
            super.onConfigurationChanged(newConfig);
            setLocale();
        }
    
        private void setLocale() {
    
            final Resources resources = getResources();
            final Configuration configuration = resources.getConfiguration();
            final Locale locale = getLocale(this);
            if (!configuration.locale.equals(locale)) {
                configuration.setLocale(locale);
                resources.updateConfiguration(configuration, null);
            }
        }
    }
    

    Note that getLocale() it's the same as above.

    That's all! I hope this can help somebody.

提交回复
热议问题