美文网首页
android多语言切换,解决横竖屏切换语言混乱的问题

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

作者: 淡淡me | 来源:发表于2019-12-19 20:19 被阅读0次

步骤一

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

相关文章

网友评论

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

      本文链接:https://www.haomeiwen.com/subject/dlevnctx.html