androd7.0 语言切换及7.0之前

在activity 或 继承自基类activity 重写以下方法:

    @Override
    protected void attachBaseContext(Context context) {
        LogTools.i(TAG,"attachBaseContext");
        String lang=SharedPreferencesUtils.getString(MyApplication.mApplication,Constants.LANGUAGE_KEY,"");
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.N){
            LogTools.i(TAG,"7.0===="+lang);
            if(lang.length()>0){
                Resources resources = context.getResources();
                String[] lc=lang.split("_");
                Locale locale = new Locale(lc[0], lc[1]);
                Configuration configuration = resources.getConfiguration();
                configuration.setLocale(locale);
                super.attachBaseContext(context.createConfigurationContext(configuration));
            }else{
                super.attachBaseContext(context);
            }
        }else{
            LogTools.i(TAG,"7.0之前="+lang);
            if(lang.length()>0) {
                //存储当前语言代码
                String[] lc = lang.split("_");
                Resources res = context.getResources();
                DisplayMetrics dm = res.getDisplayMetrics();
                Configuration conf = res.getConfiguration();
                conf.setLocale(new Locale(lc[0], lc[1]));
                //更新配置
                res.updateConfiguration(conf, dm);
            }
            super.attachBaseContext(context);
        }
    }

点击切换 方法:

    public void changeAppLanguage() {
        // "zh_CN"/"en_US" 语言代码存入本地
        SharedPreferencesUtils.setString(context,Constants.LANGUAGE_KEY,"en_US");
        Intent intent = new Intent(context, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        context.startActivity(intent);
        LogTools.i(TAG,"changeAppLanguage");
    }

顺便提个布局建议:阿拉伯语言 切换时 布局错乱问题,在根布局下加入一行代码:

android:layoutDirection="ltr"

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值