我如何获得用户的当前区域在Android?
我可以得到默认的一个,但这可能不是当前的一个,对吗?
基本上,我想要当前地区的两个字母的语言代码。不是默认的。没有Locale.current()
我如何获得用户的当前区域在Android?
我可以得到默认的一个,但这可能不是当前的一个,对吗?
基本上,我想要当前地区的两个字母的语言代码。不是默认的。没有Locale.current()
当前回答
如果你正在使用Android支持库,你可以使用ConfigurationCompat代替@Makalele的方法来摆脱弃用警告:
Locale current = ConfigurationCompat.getLocales(getResources().getConfiguration()).get(0);
或者用科特林语:
val currentLocale = ConfigurationCompat.getLocales(resources.configuration)[0]
其他回答
我使用了这个简单的代码:
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;
}
}
从getDefault的文档:
返回用户的首选语言环境。这可能已经被这个进程的setDefault(Locale)覆盖了。
同样来自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();
}
}
如果你正在使用Android支持库,你可以使用ConfigurationCompat代替@Makalele的方法来摆脱弃用警告:
Locale current = ConfigurationCompat.getLocales(getResources().getConfiguration()).get(0);
或者用科特林语:
val currentLocale = ConfigurationCompat.getLocales(resources.configuration)[0]