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

落爺英雄遲暮 提交于 2019-11-28 02:27:34

问题


I was doing this way:

context.getResources().getConfiguration().locale

Configuration.locale is deprecated if target is 24. So I made this change:

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

Now it says that it's only for minSdkVersion 24, so I cannot use it because my min target is lower.

What's the right method?


回答1:


Check which version you're running on and fallback to the deprecated solution:

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



回答2:


You could use Locale.getDefault(), which is the Java standard way of getting the current Locale.




回答3:


In Configuration.java, there is:

/**
 * ...
 * @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);

So basically using locale basically returns the primary locale the user sets. The accept answer does exactly the same as reading locale directly.

However this locale isn't necessarily the one used when getting resources. It might be the user's secondary locale if the primary locale isn't available.

Here's a more correct version:

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


来源:https://stackoverflow.com/questions/38267213/how-to-get-the-current-locale-api-level-24

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!