Android布局访问特定区域字符串及动态切换区域设置问题
Android 动态切换区域设置(Locale)实现方案
嘿,我整理了一套在Android中动态切换区域设置的可行方案,具体实现如下:
1. 初始化配置并指定目标Locale
首先基于当前应用的资源配置创建Configuration实例,然后设置你想要切换的目标语言(这里以西班牙语es为例):
Configuration mConfiguration = new Configuration(getApplicationContext().getResources().getConfiguration()); mConfiguration.setLocale(new Locale("es"));
2. 封装多语言字符串获取方法
通过createConfigurationContext生成对应配置的上下文,再从中获取字符串资源,这样就能拿到对应语言的文案了:
public static String getString(int id) { return getApplicationContext().createConfigurationContext(mConfiguration).getResources().getString(id); }
3. 准备多语言资源文件
别忘了为每种需要支持的语言创建独立的资源文件夹,比如:
- 西班牙语:
res/values-es/strings.xml - 英语:
res/values-en/strings.xml - 简体中文:
res/values-zh-rCN/strings.xml
💡 小提示:如果你的应用适配Android 7.0(API 24)及以上版本,setLocale方法已经被标记为过时,推荐使用setLocales方法替代,示例代码如下:
mConfiguration.setLocales(new LocaleList(new Locale("es")));
内容的提问来源于stack exchange,提问作者chabu
相关产品推荐
相关产品推荐

