android多语言切换,解决横竖屏切换语言混乱的问题

2019-12-19  本文已影响0人  淡淡me

步骤一

public class LanguageUtil {
    public static ContextWrapper wrap(Context context) {
        Resources res = context.getResources();
        Configuration configuration = res.getConfiguration();
        //获得你想切换的语言,可以用SharedPreferences保存读取
        Locale newLocale = getLanguageLocale(context);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            configuration.setLocale(newLocale);
            LocaleList localeList = new LocaleList(newLocale);
            LocaleList.setDefault(localeList);
            configuration.setLocales(localeList);
            context = context.createConfigurationContext(configuration);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            configuration.setLocale(newLocale);
            context = context.createConfigurationContext(configuration);
        } else {
            configuration.locale = newLocale;
            res.updateConfiguration(configuration, res.getDisplayMetrics());
        }
        return new ContextWrapper(context);
    }
}

步骤二

修改BaseActvity的attachBaseContext方法

@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(LanguageUtil.wrap(newBase));
}

步骤三

修改Application中的attachBaseContext

@Override
protected void attachBaseContext(Context base) {
  if (base == null) {
    super.attachBaseContext(null);
  }else{
    super.attachBaseContext(LanguageUtil.wrap(base));
  }
  ...
}

步骤四

切换语言时,需要重启app

LanguageUtil.setLanguageType(this, selectedLanguage);//保存修改的语言到本地
Intent it = new Intent(LoginActivity.this, LoginActivity.class);
it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(it);
android.os.Process.killProcess(android.os.Process.myPid());

参考网站

Android N change language programmatically

上一篇 下一篇

猜你喜欢

热点阅读