Android app内语言环境切换 附Demo

app内语言的切换是现在比较常见的功能,确实方便用户进行语言间的切换。先说一下整体思路,用户在做语言切换操作时做Configuration配置处理,当前操作页面recreate。将用户选择语言通过sp记录在本地,7.0之前系统直接改变Configuration的local属性就可以做到语言切换,7.0以后需要在页面的attachBaseContext方法做createConfigurationContext处理。

上图先
在这里插入图片描述

Configuration类
语言切换,主要是Configuration类的配置。通过设置Configuration 的 locale 属性来切换语言环境。local包含语言、国家等信息。
需要注意的是。7.0版本以后的语言是一个列表:
在这里插入图片描述
Google把语言这一块进行了较大的调整,系统会根据这个列表的优先级去适配语言。所以7.0以后的语言配置有所改变:

Configuration环境配置

 Context context = UIUtils.getContext().getApplicationContext();
            Configuration configuration = context.getResources().getConfiguration();
			//7.0以后
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                configuration.setLocale(userLocale);
            } else {
                configuration.locale = userLocale;
            }
            DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
            context.getResources().updateConfiguration(configuration, displayMetrics);
            saveUserLocale(userLocale);

7.0后需要在activity的attachBaseContext中进行处理,一般是在baseActivity中操作

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


  @TargetApi(Build.VERSION_CODES.N)
    public static Context updateResources(Context context) {
        Resources resources = context.getResources();
        Locale locale = getUserLocale();// getSetLocale方法是获取新设置的语言

        Configuration configuration = resources.getConfiguration();
        configuration.setLocale(locale);
        configuration.setLocales(new LocaleList(locale));
        return context.createConfigurationContext(configuration);
    }

补充一点
如果有资源文件是代码中动态获取的,7.0以上getResources也是要更新Configuration操作的,不然刚刚切换是拿不到正确的语言环境下资源的

 /**
     * 获取资源
     */
    public static Resources getResources() {
        Resources resources = getContext().getResources();
        Configuration config = resources.getConfiguration();
        DisplayMetrics dm = resources.getDisplayMetrics();// 获得屏幕参数:主要是分辨率,像素等。
        config.locale = LanguageUtil.getUserLocale();
        resources.updateConfiguration(config, dm);
        return resources;
    }

语言切换Demo

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值