如何在Android中获取用户当前的区域设置?
我可以得到默认值,但这可能不是当前的正确吗?
基本上我想要当前语言环境中的双字母语言代码.不是默认的.没有Locale.current()
Dev*_*red 466
默认值Locale是在运行时为系统属性设置中的应用程序进程静态构造的,因此它将表示启动应用程序时该Locale设备上的选定内容.通常,这很好,但它确实意味着如果用户在应用程序进程运行后更改其设置,则可能不会立即更新值.LocalegetDefaultLocale()
如果由于某种原因需要在应用程序中捕获此类事件,则可以尝试Locale从资源Configuration对象中获取可用的事件,即
Locale current = getResources().getConfiguration().locale;
Run Code Online (Sandbox Code Playgroud)
如果您的应用程序需要更改设置,您可能会发现更快地更新此值.
Mak*_*ele 160
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;
}
}
Run Code Online (Sandbox Code Playgroud)
Ele*_*gyD 50
如果您使用的是Android支持库,则可以使用ConfigurationCompat而不是@ Makalele的方法来消除删除警告:
Locale current = ConfigurationCompat.getLocales(getResources().getConfiguration()).get(0);
Run Code Online (Sandbox Code Playgroud)
或在Kotlin:
val currentLocale = ConfigurationCompat.getLocales(resources.configuration)[0]
Run Code Online (Sandbox Code Playgroud)
kab*_*uko 13
来自getDefault的文件:
返回用户的首选语言环境.可能已使用setDefault(Locale)覆盖此进程.
同样来自Locale文档:
默认语言环境适用于涉及向用户显示数据的任务.
好像你应该只使用它.
小智 8
All answers above - do not work. So I will put here a function that works on 4 and 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();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
170142 次 |
| 最近记录: |