Почему этот код не меняет весь язык моего приложения? - PullRequest
0 голосов
/ 27 марта 2019

Я написал код ниже, чтобы изменить язык приложения, и он не меняет весь язык приложения:

public class SettingsFragment extends PreferenceFragment implements 
          Preference.OnPreferenceChangeListener {

    private PrefHelper prefHelper;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.pref);

        prefHelper = new PrefHelper(getActivity());

        ListPreference langPreference = (ListPreference) findPreference(prefHelper.PREF_KEY_LANG);
        langPreference.setOnPreferenceChangeListener(this);
        langPreference.setSummary(langPreference.getEntry());
    }

    @Override
    public boolean onPreferenceChange(Preference preference, Object newValue) {
        if (prefHelper.PREF_KEY_LANG.equals(preference.getKey())) {
            changeLang((String) newValue);
            return true;
        }
        return true;
    }

    private void changeLang(String lang) {
        prefHelper.setLang(lang);

        WeakReference<Context> cReference = new WeakReference<>(getActivity());
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        PendingIntent intent = PendingIntent.getActivity(cReference.get(), 0,
            new Intent(new Intent(getActivity().getApplicationContext(), QuestionsActivity.class)), 0);

        AlarmManager mgr = (AlarmManager) getActivity().getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, intent);

        System.exit(1);
    }
}

Кто-нибудь может сказать, в чем проблема?

Я создал два отдельных файла eng.xml и rus.xml.

Ответы [ 2 ]

1 голос
/ 27 марта 2019

Для работы на всех APIS Используйте этот код в Activity

 override fun attachBaseContext(base: Context) {
    super.attachBaseContext(LocaleHelper.updateBaseContextLocale(base))
}

и

object LocaleHelper {
    fun updateBaseContextLocale(baseContext: Context): Context {
        val localeManager = LocaleManagerImpl(SharedPrefsStorage(baseContext))
        val locale = localeManager.locale
        Locale.setDefault(locale)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return updateResourcesLocale(baseContext, locale)
        } else {
            return updateResourcesLocaleLegacy(baseContext, locale)
        }
    }

    @TargetApi(Build.VERSION_CODES.N)
    private fun updateResourcesLocale(context: Context, locale: Locale): Context {
        val configuration = context.resources.configuration
        configuration.setLocale(locale)
        return context.createConfigurationContext(configuration)
    }

    private fun updateResourcesLocaleLegacy(context: Context, locale: Locale): Context {
        val resources = context.resources
        val configuration = resources.configuration
        configuration.locale = locale
        resources.updateConfiguration(configuration, resources.displayMetrics)
        return context
    }

    fun updateApplicationContextLocale(applicationContext: Context,
                                       localeConfiguration: Configuration,
                                       locale: Locale) {
        applicationContext.resources.updateConfiguration(localeConfiguration,
                applicationContext.resources.displayMetrics)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            applicationContext.createConfigurationContext(localeConfiguration)
        } else {
            Locale.setDefault(locale)
            val config = applicationContext.resources.configuration
            config.locale = locale
            applicationContext.resources.updateConfiguration(config,
                    applicationContext.resources.displayMetrics)
        }
    }

    fun getCurrentLocale(resources: Resources): Locale {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            resources.configuration.locales[0]
        } else {
            resources.configuration.locale
        }    
    }
}

Кроме того, когда вы хотите изменить его во время выполнения, просто используйте функцию create () в Activity

.

Это единственный способ, с помощью которого я понял, изменив локаль на все API и все ресурсы. Вы не избежите использования устаревшего кода, если захотите заставить его работать.

0 голосов
/ 27 марта 2019

Я использую вот так и работаю нормально

 public static void changeLocale(Resources res, String locale) {

    Configuration config;
    config = new Configuration(res.getConfiguration());

    switch (locale) {
        case "th":
            config.locale = new Locale("th");
            break;
        case "TH":
            config.locale = new Locale("th");
            break;
        default:
            config.locale = Locale.ENGLISH;
            break;
    }

    res.updateConfiguration(config, res.getDisplayMetrics());

}

, затем позвоните в любое место из вашего приложения, как показано ниже

LanguageHelper.changeLocale(resources, "th")

Затем перезапустите намерение, как это

Intent restart = getIntent();
finish();
startActivity(restart);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...