android语言 选择题,Android N以编程方式更改语言

首先,你应该知道在25个API Resources.updateConfiguration(...)中已弃用。因此,你可以执行以下操作:

1)你需要创建自己的ContextWrapper,它将覆盖baseContext中的所有配置参数。例如,这是我的ContextWrapper,可以正确更改Locale。注意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);

}

注意:

如果要在某个地方更改应用程序的区域设置,请记住要重新创建活动。你可以使用此解决方案覆盖所需的任何配置。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值