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

前端 未结 3 1301
广开言路
广开言路 2020-12-18 18:11

I was doing this way:

context.getResources().getConfiguration().locale

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

3条回答
  •  青春惊慌失措
    2020-12-18 18:31

    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,
     * getLocales().get(0) 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;
    

提交回复
热议问题