Change language programmatically (Android N 7.0 - API 24)

后端 未结 3 1084

I\'m using the following code to set specific language in my app. Language is saved into SharedPreferences within the app. And it works perfectly up to

3条回答
  •  时光取名叫无心
    2020-12-14 05:31

    Create a new class extends ContextWrapper

    public class MyContextWrapper extends ContextWrapper {
        public MyContextWrapper(Context base) {
            super(base);
        }
    
        @TargetApi(Build.VERSION_CODES.N)
        public static ContextWrapper wrap(Context context, Locale newLocale) {
            Resources res = context.getResources();
            Configuration configuration = res.getConfiguration();
    
            if (VersionUtils.isAfter24()) {
                configuration.setLocale(newLocale);
    
                LocaleList localeList = new LocaleList(newLocale);
                LocaleList.setDefault(localeList);
                configuration.setLocales(localeList);
    
                context = context.createConfigurationContext(configuration);
    
            } else if (VersionUtils.isAfter17()) {
                configuration.setLocale(newLocale);
                context = context.createConfigurationContext(configuration);
    
            } else {
                configuration.locale = newLocale;
                res.updateConfiguration(configuration, res.getDisplayMetrics());
            }
    
            return new ContextWrapper(context);
        }
    }
    

    override Activity's attachBaseContext method

    @Override
    protected void attachBaseContext(Context newBase) {
        Locale languageType = LanguageUtil.getLanguageType(mContext);
        super.attachBaseContext(MyContextWrapper.wrap(newBase, languageType));
    }
    

    finish the activity and start it again,new locale will become effective.

    demo:https://github.com/fanturbo/MultiLanguageDemo

提交回复
热议问题