Android: How to get string in specific locale WITHOUT changing the current locale

前端 未结 5 2006

Use Case: Logging error messages as displayed to the user.

However you don\'t want to have messages in your log that depend on the locale of the user\'s device. On t

5条回答
  •  渐次进展
    2020-12-05 07:07

    For api +17 we could use this:

    public static String getDefaultString(Context context, @StringRes int stringId){
        Resources resources = context.getResources();
        Configuration configuration = new Configuration(resources.getConfiguration());
        Locale defaultLocale = new Locale("en");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            LocaleList localeList = new LocaleList(defaultLocale);
            configuration.setLocales(localeList);
            return context.createConfigurationContext(configuration).getString(stringId);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){
            configuration.setLocale(defaultLocale);
            return context.createConfigurationContext(configuration).getString(stringId);
        }
        return context.getString(stringId);
    }
    

提交回复
热议问题