一个应用程序支持 3 种语言:
- 英语
- 简体中文
- 繁体中文
资源分别位于目录中:
- 资源/值(value)
- res/values-zh-rCN
- res/values-zh-rTW
在牛轧糖之前的版本中,所有工作都按照文档相应页面上的描述进行 - https://developer.android.com/guide/topics/resources/providing-resources.html .
目前在 Nougat 上,当用户将设备切换到来自 values-zh-rCN 的任何简体中文语言资源时。但是当用户将设备语言切换到任何繁体中文应用程序时,仍然使用来自 values-zh-rCN 的值(如果您假设没有繁体资源,这看起来像是有效行为)。最后,如果我从项目中删除目录 values-zh-rCN,应用程序将完全忽略传统资源并使用默认的英文资源。
有没有人遇到过这样的问题,除了向 Google 报告错误之外还有其他解决方案吗?
最佳答案
好的,我已经报告了这个错误 - https://code.google.com/p/android/issues/detail?id=235561
现在,我已经实现了这种解决方法,也许有人会发现它有用。
首先,我们需要创建一个 BroadcastReciever 来监听系统语言的变化:
private class LanguageChangeReceiver extends BroadcastReceiver {
public static boolean isNougatTraditionalChinese() {
return isNougat() && Locale.getDefault().toLanguageTag().contains("zh-Hant");
}
@Override
public void onReceive(Context context, Intent intent) {
if (!application.getConfiguration().isLanguageSet()) {
if (isNougatTraditionalChinese()) {
String[] supportedLangTags = context.getResources().getStringArray(R.array.language_values);
application.getConfiguration().setLanguagePreference(supportedLangTags[2]);
application.updateLanguage();
}
}
}
}
...在应用程序语言更新中看起来大致如此...
private void updateLanguage(String langTag) {
Locale myLocale = L10nUtils.createLocaleByTag(langTag);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
android.content.res.Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
}
... 并在上下文中注册 BroadcastReciever ...
context.registerReceiver(new LanguageChangeReceiver(), new IntentFilter(Intent.ACTION_LOCALE_CHANGED));
关于Android Nougat 忽略位于 res/values-zh-rTW 中的字符串资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42505660/