我有以下代码:
/**
* Sets a new Locale for the APP.
* @param newLocale - Valid new locale.
*/
private static void setLocale( String newLocale )
{
Locale locale = new Locale( newLocale );
Locale.setDefault( locale );
Configuration config = new Configuration();
config.locale = locale;
context.getResources().updateConfiguration( config, context.getResources().getDisplayMetrics() );
}
Run Code Online (Sandbox Code Playgroud)
简单.
然而,当我在智能手机(4.1.1)中运行它时,它确实可以正常工作.设备更改字符串以匹配语言.
但是对于平板电脑(4.3),它不起作用.如果我输出如下内容:
Log.d("TAG",Locale.getDefault());
Run Code Online (Sandbox Code Playgroud)
Locale似乎在两台设备上都有所改变,但正如我所说,Strings没有被翻译成正确的语言.
我做了很多调试,我发现了对象之间的区别:查看4.1.1上的Configuration对象:

并查看平板电脑上的配置对象(4.3)

正如您所看到的,唯一值得注意的差异是userSetLocale在平板电脑上设置为False.
所以我检查了Google SourceCode(https://github.com/android/platform_frameworks_base/blob/master/core/java/android/content/res/Configuration.java),它说明:
/**
* Locale should persist on setting. This is hidden because it is really
* questionable whether this is the right way to expose the functionality.
* @hide
*/
public boolean userSetLocale;
Run Code Online (Sandbox Code Playgroud)
看起来这对我有影响.因为我无法访问此值,也无法通过getter/setter或公共访问,我使用反射来更改它.
然而,在通过反射改变之后,即使我已经看到它在内部发生了变化(反射后boolean设置为false),同样的问题仍然存在.
你们有什么提示吗?
同时我会继续测试.
谢谢. 测试:
这是我用于本地化的代码。有100万人使用它,并且从未听说过关于不更改字符串的任何抱怨,因此我希望它也对您有用:
在课堂上:
Locale myLocale;
Run Code Online (Sandbox Code Playgroud)
功能:
public void setLocale(String lang) {
myLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
reloadUI(); // you may not need this, in my activity ui must be refreshed immediately so it has a function like this.
}
Run Code Online (Sandbox Code Playgroud)
函数调用:
//example for setting English
setLocale("en_gb");
Run Code Online (Sandbox Code Playgroud)
出色地,
用户 SC Sir 提供了一个有效的答案。但我的代码也有效。我们面临的问题是单个设备忽略了此区域设置更改。所以据我所知,它只是一个设备,而且可能是由于 ROM 有问题造成的,因为它是 Genymotion 模拟器。
总的来说,答案是:
干杯。
| 归档时间: |
|
| 查看次数: |
5050 次 |
| 最近记录: |