Android程序语言JAVA,java – Android N以编程方式更改语言

好.最后我设法找到一个解决方案.

首先你应该知道在25 API资源.updateConfiguration(…)已被弃用.所以你可以这样做:

1)您需要创建自己的ContextWrapper来覆盖baseContext中的所有配置参数.例如,这是我的ContextWrapper正确更改语言环境.注意context.createConfigurationContext(configuration)方法.

public class ContextWrapper extends android.content.ContextWrapper {

public ContextWrapper(Context base) {

super(base);

}

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

Resources res = context.getResources();

Configuration configuration = res.getConfiguration();

if (BuildUtils.isAtLeast24Api()) {

configuration.setLocale(newLocale);

LocaleList localeList = new LocaleList(newLocale);

LocaleList.setDefault(localeList);

configuration.setLocales(localeList);

context = context.createConfigurationContext(configuration);

} else if (BuildUtils.isAtLeast17Api()) {

configuration.setLocale(newLocale);

context = context.createConfigurationContext(configuration);

} else {

configuration.locale = newLocale;

res.updateConfiguration(configuration, res.getDisplayMetrics());

}

return new ContextWrapper(context);

}}

2)您的BaseActivity应该如何做?

@Override

protected void attachBaseContext(Context newBase) {

Locale newLocale;

// .. create or get your new Locale object here.

Context context = ContextWrapper.wrap(newBase, newLocale);

super.attachBaseContext(context);

}

如果要在App中更改“区域设置”,请记住重新创建活动.您可以使用此解决方案覆盖您想要的任何配置.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值