31

我是这样做的:

context.getResources().getConfiguration().locale

Configuration.locale如果目标是 24,则不推荐使用。所以我做了这个改变:

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

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

什么是正确的方法?

4

4 回答 4

60

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

Locale locale;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    locale = context.getResources().getConfiguration().getLocales().get(0);
} else {
    locale = context.getResources().getConfiguration().locale;
}
于 2016-07-08T12:58:48.907 回答
6

您可以使用Locale.getDefault(),这是获取当前Locale.

于 2016-07-08T13:13:20.687 回答
3

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基本上返回用户设置的主要语言环境。接受答案与直接阅读完全相同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;
于 2016-10-08T15:16:19.903 回答
2

这是使用ConfigurationCompat该类的单线:

ConfigurationCompat.getLocales(context.getResources().getConfiguration()).get(0)
于 2021-04-15T16:24:08.410 回答