如何在Android设备中选择当前语言?


当前回答

你可以尝试从系统资源中获取locale:

PackageManager packageManager = context.getPackageManager();
Resources resources = packageManager.getResourcesForApplication("android");
String language = resources.getConfiguration().locale.getLanguage();

其他回答

以上答案没有区分简体中文和繁体中文。 Locale.getDefault(). tostring()工作,返回“zh_CN”,“zh_TW”,“en_US”等。

参考:https://developer.android.com/reference/java/util/Locale.html, ISO 639-1是旧的。

我检查了我的Android 4.1.2设备上的Locale方法,结果是:

Locale.getDefault().getLanguage()       ---> en      
Locale.getDefault().getISO3Language()   ---> eng 
Locale.getDefault().getCountry()        ---> US 
Locale.getDefault().getISO3Country()    ---> USA 
Locale.getDefault().getDisplayCountry() ---> United States 
Locale.getDefault().getDisplayName()    ---> English (United States) 
Locale.getDefault().toString()          ---> en_US
Locale.getDefault().getDisplayLanguage()---> English
Locale.getDefault().toLanguageTag()     ---> en-US

其他人对设备语言给出了很好的答案,

如果您希望使用应用程序语言,最简单的方法是在strings.xml文件中添加一个app_lang键,并为每个语言指定lang。

这样,如果你的应用程序的默认语言与设备语言不同,你可以选择将其作为服务的参数发送。

为了节省其他人的时间和/或混乱,我想分享我已经尝试了上面Johan Pelgrim提出的两个替代方案,在我的设备上它们是等效的——无论默认位置是否改变。

所以我的设备的默认设置是英语(英国),在这种状态下,约翰的回答中的两个字符串都给出了相同的结果。如果我然后在电话设置中更改区域设置(说到italiano(意大利))并重新运行,那么在Johan的回答中两个字符串都将区域设置为italiano(意大利)。

因此,我认为Johan最初的帖子是正确的,而gregm的评论是不正确的。

获取设备语言的正确方法如下:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    return context.getResources().getConfiguration().getLocales().get(0);
} else {
    return context.getResources().getConfiguration().locale;
}

希望能有所帮助。