Android 7.0以上版本,如何实现应用内语言切换

7.0系统之前,系统语言的设置是一种;
7.0以后,系统语言的设置是一组;
所以,导致以前的设置语言的方法过时了,到了8.0就不能再起作用了。

原来的设置语言代码:
这里写图片描述

现在的需要区分版本设置:

public class MyContextWrapper extends android.content.ContextWrapper {

public MyContextWrapper(Context base) {
    super(base);
}

public static ContextWrapper wrap(Context context, Locale newLocale) {

    Resources res = context.getResources();
    Configuration configuration = res.getConfiguration();

    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.KITKAT) {

        configuration.setLocale(newLocale);
        context = context.createConfigurationContext(configuration);

    }

    return new ContextWrapper(context);
} }

接下来,只要重写BaseActivity的onAttachBaseContext方法:

@Override
protected void attachBaseContext(Context newBase) {
Locale newLocale;
// .. create or get your new Locale object here.

    Context context = MyContextWrapper.wrap(newBase, newLocale);
    super.attachBaseContext(context);
}

OK了,这样子就不会在7.0系统以上出现问题了。

参考自:https://www.jianshu.com/p/32ff13db1f0d

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值