我如何获得用户的当前区域在Android?
我可以得到默认的一个,但这可能不是当前的一个,对吗?
基本上,我想要当前地区的两个字母的语言代码。不是默认的。没有Locale.current()
我如何获得用户的当前区域在Android?
我可以得到默认的一个,但这可能不是当前的一个,对吗?
基本上,我想要当前地区的两个字母的语言代码。不是默认的。没有Locale.current()
当前回答
根据官方文档,ConfigurationCompat在支持库中已弃用
您可以考虑使用
LocaleListCompat.getDefault()[0].toLanguageTag()第0个位置将是用户首选的语言环境
在第0个位置获得默认区域将是 LocaleListCompat.getAdjustedDefault ()
其他回答
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;
}
}
如果你正在使用Android支持库,你可以使用ConfigurationCompat代替@Makalele的方法来摆脱弃用警告:
Locale current = ConfigurationCompat.getLocales(getResources().getConfiguration()).get(0);
或者用科特林语:
val currentLocale = ConfigurationCompat.getLocales(resources.configuration)[0]
现在,我们可以使用ConfigurationCompat类来避免警告和不必要的样板。
Locale current = ConfigurationCompat.getLocales(getResources().getConfiguration()).get(0);
根据官方文档,ConfigurationCompat在支持库中已弃用
您可以考虑使用
LocaleListCompat.getDefault()[0].toLanguageTag()第0个位置将是用户首选的语言环境
在第0个位置获得默认区域将是 LocaleListCompat.getAdjustedDefault ()
从getDefault的文档:
返回用户的首选语言环境。这可能已经被这个进程的setDefault(Locale)覆盖了。
同样来自Locale文档:
默认区域设置适用于涉及向用户显示数据的任务。
看来你应该直接用它。