如何获取当前语言环境(API 级别 24)?

How to get the current locale (API level 24)?

我是这样做的:

context.getResources().getConfiguration().locale
如果目标为 24,

Configuration.locale 已弃用。所以我做了这个更改:

context.getResources().getConfiguration().getLocales().get(0)

现在它说它只适用于 minSdkVersion 24,所以我不能使用它,因为我的最低目标较低。

正确的方法是什么?

检查您 运行 使用的版本并回退到已弃用的解决方案:

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

您可以使用 Locale.getDefault(),这是 Java 获取当前 Locale 的标准方法。

Configuration.java中,有:

/**
 * ...
 * @deprecated Do not set or read this directly. Use {@link #getLocales()} and
 * {@link #setLocales(LocaleList)}. If only the primary locale is needed,
 * <code>getLocales().get(0)</code> is now the preferred accessor.
 */
@Deprecated public Locale locale;
...
configOut.mLocaleList = LocaleList.forLanguageTags(localesStr);
configOut.locale = configOut.mLocaleList.get(0);

所以基本上使用 locale 基本上 returns 用户设置的 主要 语言环境。接受答案与直接阅读 locale 完全相同。

但是,此语言环境不一定是获取资源时使用的语言环境。如果主要区域设置不可用,它可能是用户的次要区域设置。

这是一个更正确的版本:

Resources resources = context.getResources();
Locale locale = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
        ? resources.getConfiguration().getLocales()
            .getFirstMatch(resources.getAssets().getLocales())
        : resources.getConfiguration().locale;

这是使用 ConfigurationCompat class 的单行代码:

ConfigurationCompat.getLocales(context.getResources().getConfiguration()).get(0)