如何在Android设备中选择当前语言?
当前回答
如果API级别为24或以上,则使用LocaleList.getDefault().get(0).getLanguage() 否则使用Locale.getDefault.getLanguage()
private fun getSystemLocale() = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
LocaleList.getDefault().get(0).language
} else {
Locale.getDefault().language
}
参考:https://developer.android.com/guide/topics/resources/multilingual-support
其他回答
有两种语言。
操作系统默认语言:
Locale.getDefault().getDisplayLanguage();
目前申请语言:
getResources().getConfiguration().locale.getDisplayLanguage();//return string
为了节省其他人的时间和/或混乱,我想分享我已经尝试了上面Johan Pelgrim提出的两个替代方案,在我的设备上它们是等效的——无论默认位置是否改变。
所以我的设备的默认设置是英语(英国),在这种状态下,约翰的回答中的两个字符串都给出了相同的结果。如果我然后在电话设置中更改区域设置(说到italiano(意大利))并重新运行,那么在Johan的回答中两个字符串都将区域设置为italiano(意大利)。
因此,我认为Johan最初的帖子是正确的,而gregm的评论是不正确的。
我的解是这样的
@SuppressWarnings("deprecation")
public String getCurrentLocale2() {
return Resources.getSystem().getConfiguration().locale.getLanguage();
}
@TargetApi(Build.VERSION_CODES.N)
public Locale getCurrentLocale() {
getResources();
return Resources.getSystem().getConfiguration().getLocales().get(0);
}
然后
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Log.e("Locale", getCurrentLocale().getLanguage());
} else {
Log.e("Locale", getCurrentLocale2().toString());
}
显示——>和
您可以从当前区域“提取”语言。你可以通过标准的Java API或者使用Android Context来提取语言环境。例如,下面这两行是等价的:
String locale = context.getResources().getConfiguration().locale.getDisplayName();
String locale = java.util.Locale.getDefault().getDisplayName();
下面是获取设备国家的代码。兼容所有版本的android甚至奥利奥。
解决方案:如果用户没有sim卡,那么在手机设置或当前语言选择时获取他所使用的国家。
public static String getDeviceCountry(Context context) {
String deviceCountryCode = null;
final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if(tm != null) {
deviceCountryCode = tm.getNetworkCountryIso();
}
if (deviceCountryCode != null && deviceCountryCode.length() <=3) {
deviceCountryCode = deviceCountryCode.toUpperCase();
}
else {
deviceCountryCode = ConfigurationCompat.getLocales(Resources.getSystem().getConfiguration()).get(0).getCountry().toUpperCase();
}
// Log.d("countryCode"," : " + deviceCountryCode );
return deviceCountryCode;
}
推荐文章
- 如何模拟Android杀死我的进程
- 禁用EditText闪烁光标
- Android Eclipse -无法找到*.apk
- 设置TextView文本从html格式的字符串资源在XML
- 如何允许所有网络连接类型HTTP和HTTPS在Android(9)馅饼?
- Android加载JS包失败
- Android Studio, logcat在应用程序关闭后清理
- 在android中从上下文获取活动
- 无法解析主机"<URL here>"没有与主机名关联的地址
- getActivity()在Fragment函数中返回null
- 按钮背景是透明的
- 在Mac OS X上哪里安装Android SDK ?
- 我如何获得图像缩放功能?
- 在Android应用程序中显示当前时间和日期
- BottomSheetDialogFragment的圆角