我是这样做的:
context.getResources().getConfiguration().locale
Configuration.locale
如果目标是 24,则不推荐使用。所以我做了这个改变:
context.getResources().getConfiguration().getLocales().get(0)
现在它说它只适用于minSdkVersion
24,所以我不能使用它,因为我的最小目标较低。
什么是正确的方法?
我是这样做的:
context.getResources().getConfiguration().locale
Configuration.locale
如果目标是 24,则不推荐使用。所以我做了这个改变:
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()
,这是获取当前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
基本上返回用户设置的主要语言环境。接受答案与直接阅读完全相同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
该类的单线:
ConfigurationCompat.getLocales(context.getResources().getConfiguration()).get(0)