l3ger0j / Questopia

Android fork port of Quest Soft Player
Apache License 2.0
16 stars 2 forks source link

Revise the language selection system, make it more encapsulated and independent of any view #3

Closed l3ger0j closed 1 year ago

l3ger0j commented 1 year ago

The current language system looks like this:

in LanguageUtil

    private static String currentLanguage = Locale.getDefault().getLanguage();

    public static String getCurrentLanguage() {
        return currentLanguage;
    }

    public static void setLocaleOnContext(Context context, String lang) {
        if (!currentLanguage.equals(lang)) {
            var locale = new Locale(lang);
            var res = context.getResources();
            var dm = res.getDisplayMetrics();
            var conf = res.getConfiguration();
            conf.locale = locale;
            currentLanguage = locale.getLanguage();
            res.updateConfiguration(conf , dm);
        }
    }

    public static void setLocaleOnActivity(Activity activity, String languageCode) {
        if (!currentLanguage.equals(languageCode)) {
            Locale locale = new Locale(languageCode);
            Locale.setDefault(locale);
            var resources = activity.getResources();
            var config = resources.getConfiguration();
            config.setLocale(locale);
            resources.updateConfiguration(config , resources.getDisplayMetrics());
            currentLanguage = locale.getLanguage();
        }
    }

in class-consumer (e.g. SettingsActivity)

    private String currentLanguage = Locale.getDefault().getLanguage();

    private void loadLocale() {
        setLocale(this, settingsController.language);
        currentLanguage = settingsController.language;
    }

    @Override
    protected void onResume() {
        super.onResume();
        settingsController = SettingsController.newInstance().loadSettings(this);
        updateLocale();
    }
    private void updateLocale() {
        if (currentLanguage.equals(settingsController.language)) return;
        setLocale(this, settingsController.language);
        currentLanguage = settingsController.language;
    }

Problems caused by using this system:

  1. The problem with determining the current language is because the Locale method.getDefault() returns the value defined at startup;
  2. The problem associated with creating something using a subset of R.string;
  3. The problem with portability and code volume.

The solution is to switch to the Language API