动态更改应用程序上下文的语言环境

时间:2013-11-20 18:42:30

标签: java android locale

我是Java和Android新手。我通过处理一些单元测试开始使用该平台,并且我有一个我想要测试的日期方法,它将当前context作为参数。我想moc这个上下文并指定我选择的语言环境独立于当前设备设置。

这是可能的,任何人都可以告诉我该怎么做?

我尝试创建一个扩展Application的自定义类,并覆盖设置该语言环境的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();
谢谢你!

1 个答案:

答案 0 :(得分:0)

更改区域设置时,您指定的是完整区域设置“en_GB”。这不起作用。根据{{​​3}},您需要单独指定语言和国家/地区

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

根据我的经验,如果您指定了错误的区域设置,设备将只使用默认区域设置

相关问题