我如何获得用户的当前区域在Android?

我可以得到默认的一个,但这可能不是当前的一个,对吗?

基本上,我想要当前地区的两个字母的语言代码。不是默认的。没有Locale.current()


当前回答

如果你正在使用Android支持库,你可以使用ConfigurationCompat代替@Makalele的方法来摆脱弃用警告:

Locale current = ConfigurationCompat.getLocales(getResources().getConfiguration()).get(0);

或者用科特林语:

val currentLocale = ConfigurationCompat.getLocales(resources.configuration)[0]

其他回答

我用过这个:

String currentLanguage = Locale.getDefault().getDisplayLanguage();
if (currentLanguage.toLowerCase().contains("en")) {
   //do something
}

如果你正在使用Android支持库,你可以使用ConfigurationCompat代替@Makalele的方法来摆脱弃用警告:

Locale current = ConfigurationCompat.getLocales(getResources().getConfiguration()).get(0);

或者用科特林语:

val currentLocale = ConfigurationCompat.getLocales(resources.configuration)[0]

从getDefault的文档:

返回用户的首选语言环境。这可能已经被这个进程的setDefault(Locale)覆盖了。

同样来自Locale文档:

默认区域设置适用于涉及向用户显示数据的任务。

看来你应该直接用它。

我使用了这个简单的代码:

if(getResources().getConfiguration().locale.getLanguage().equalsIgnoreCase("en"))
{
   //do something
}

现在,我们可以使用ConfigurationCompat类来避免警告和不必要的样板。

Locale current = ConfigurationCompat.getLocales(getResources().getConfiguration()).get(0);