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

前端 未结 5 2000

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条回答
  •  -上瘾入骨i
    2020-12-05 06:57

    You can save all the strings of the default locale in a Map inside a global class, like Application that is executed when launching the app:

    public class DualLocaleApplication extends Application {
    
        private static Map defaultLocaleString;
    
        public void onCreate() {
            super.onCreate();
            Resources currentResources = getResources();
            AssetManager assets = currentResources.getAssets();
            DisplayMetrics metrics = currentResources.getDisplayMetrics();
            Configuration config = new Configuration(
                    currentResources.getConfiguration());
            config.locale = Locale.ENGLISH;
            new Resources(assets, metrics, config);
            defaultLocaleString = new HashMap();
            Class stringResources = R.string.class;
            for (Field field : stringResources.getFields()) {
                String packageName = getPackageName();
                int resId = getResources().getIdentifier(field.getName(), "string", packageName);
                defaultLocaleString.put(resId, getString(resId));
            }
            // Restore device-specific locale
            new Resources(assets, metrics, currentResources.getConfiguration());
        }
    
        public static String getStringInDefaultLocale(int resId) {
            return defaultLocaleString.get(resId);
        }
    
    }
    

    This solution is not optimal, but you won't have concurrency problems.

提交回复
热议问题