gpt4 book ai didi

java - 动态更改应用程序上下文的区域设置

转载 作者:太空宇宙 更新时间:2023-11-04 15:23:40 25 4
gpt4 key购买 nike

我是一名刚接触 Java 和 Android 的 .NET 开发人员。我从平台开始进行一些单元测试,并且我想测试一个日期方法,该方法将当前上下文作为参数。我想模拟此上下文并指定我选择的独立于当前设备设置的区域设置。

这可能吗?谁能告诉我该怎么做?

我尝试创建一个扩展应用程序的自定义类并重写设置区域设置的onCreate方法。然后,我通过调用 getApplicationContext() 方法将其传递到我的方法中,但这似乎没有完成这项工作。这是我尝试过的:

class UKApplication extends Application
{
@Override
public void onCreate()
{
super.onCreate();
Locale locale = new Locale("en_GB");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
}
}

我还尝试设置看起来更接近的上下文配置,但是当我提取日期格式时,它似乎不会影响日期格式。

    Locale locale = new Locale("en_GB");
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;

mContext.getResources().updateConfiguration(config, mContext.getResources().getDisplayMetrics());
myStaticClass.methodToTest(mContext);

有什么建议吗?

这是使用上下文获取日期格式的代码。模式似乎总是以 MM/dd/yyyy 的形式出现:

final DateFormat shortDateFormat = android.text.format.DateFormat.getDateFormat(context.getApplicationContext());
if (shortDateFormat instanceof SimpleDateFormat) {
final String pattern = ((SimpleDateFormat) shortDateFormat).toPattern();

谢谢!

最佳答案

当您更改区域设置时,您将指定完整的区域设置“en_GB”。这是行不通的。根据documentation您需要分别指定语言和国家/地区

Locale locale = new Locale("en","GB");

根据我的经验,如果您指定了不正确的区域设置,设备将仅使用默认区域设置

关于java - 动态更改应用程序上下文的区域设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20104268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com