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

步骤一

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

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容