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

博客介绍了在APIResources.updateConfiguration(...)被弃用后,如何通过创建自定义的ContextWrapper来覆盖应用程序的配置参数,特别是在更改Locale时的方法。文章提供了详细的步骤,包括针对不同Android API级别的实现,并强调了在更改区域设置后需要重新创建活动。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先,你应该知道在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);

}

注意:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值