我如何获得用户的当前区域在Android?
我可以得到默认的一个,但这可能不是当前的一个,对吗?
基本上,我想要当前地区的两个字母的语言代码。不是默认的。没有Locale.current()
我如何获得用户的当前区域在Android?
我可以得到默认的一个,但这可能不是当前的一个,对吗?
基本上,我想要当前地区的两个字母的语言代码。不是默认的。没有Locale.current()
当前回答
我用过这个:
String currentLanguage = Locale.getDefault().getDisplayLanguage();
if (currentLanguage.toLowerCase().contains("en")) {
//do something
}
其他回答
现在,我们可以使用ConfigurationCompat类来避免警告和不必要的样板。
Locale current = ConfigurationCompat.getLocales(getResources().getConfiguration()).get(0);
我用过这个:
String currentLanguage = Locale.getDefault().getDisplayLanguage();
if (currentLanguage.toLowerCase().contains("en")) {
//do something
}
我使用了这个简单的代码:
if(getResources().getConfiguration().locale.getLanguage().equalsIgnoreCase("en"))
{
//do something
}
Android N (Api级别24)更新(无警告):
Locale getCurrentLocale(Context context){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
return context.getResources().getConfiguration().getLocales().get(0);
} else{
//noinspection deprecation
return context.getResources().getConfiguration().locale;
}
}
默认的Locale是在应用程序进程运行时从系统属性设置静态构造的,因此它将表示应用程序启动时在该设备上选择的Locale。通常情况下,这很好,但这意味着如果用户在应用程序进程运行后更改了设置中的Locale,那么getDefaultLocale()的值可能不会立即更新。
如果您在应用程序中出于某种原因需要捕获这样的事件,您可以尝试从资源Configuration对象获取可用的Locale,例如。
Locale current = getResources().getConfiguration().locale;
如果您的应用程序需要更改设置,您可能会发现在更改设置后该值更新得更快。
从评论中更新> API 24
Locale current = getResources().getConfiguration().getLocales().get(0) // is now the preferred accessor.