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


当前回答

有两种语言。

操作系统默认语言:

Locale.getDefault().getDisplayLanguage();

目前申请语言:

getResources().getConfiguration().locale.getDisplayLanguage();//return string

其他回答

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

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

希望能有所帮助。

如果你想要获得你的设备所选择的语言,这可能会帮助你:

Locale.getDefault().getDisplayLanguage();

你可以使用Locale.getDefault().getLanguage();要获得常用的语言代码(例如:“德”、“en”)

您可以从当前区域“提取”语言。你可以通过标准的Java API或者使用Android Context来提取语言环境。例如,下面这两行是等价的:

String locale = context.getResources().getConfiguration().locale.getDisplayName();
String locale = java.util.Locale.getDefault().getDisplayName();

为了节省其他人的时间和/或混乱,我想分享我已经尝试了上面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());
            }

显示——>和