我如何获得用户的当前区域在Android?
我可以得到默认的一个,但这可能不是当前的一个,对吗?
基本上,我想要当前地区的两个字母的语言代码。不是默认的。没有Locale.current()
我如何获得用户的当前区域在Android?
我可以得到默认的一个,但这可能不是当前的一个,对吗?
基本上,我想要当前地区的两个字母的语言代码。不是默认的。没有Locale.current()
当前回答
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在支持库中已弃用
您可以考虑使用
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;
}
}
以上所有答案都不行。 因此,我将在这里放置一个在4和9 android上工作的函数
private String getCurrentLanguage(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
return LocaleList.getDefault().get(0).getLanguage();
} else{
return Locale.getDefault().getLanguage();
}
}
现在,我们可以使用ConfigurationCompat类来避免警告和不必要的样板。
Locale current = ConfigurationCompat.getLocales(getResources().getConfiguration()).get(0);