Domanda

I have a preferenceFragment with PreferenceList in which the user selects the new Language for the app UI.
I want the whole resources to be refreshed and reloaded with the new language. (as if the app was restarted with the newly selected language) As i've read, the configurationChanged by its default should restart the Activity or whatever is running, but it doesn't seem to happen. (I've added a Toast in the onCreate of the activity containing the preferenceFragment and it isn't called when the configuration changed.
Here is the handling of the Language change within the preferenceFragment :

@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    if (getString(R.string.shared_options_select_language_key).equals(key)) {
        Toolkit.setApplicationLanguage(getActivity(), getActivity().getBaseContext());
    }

Here is the code for setApplicationLanguage():

public static void setApplicationLanguage(Context ctx, Context baseCtx) {

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx);

    String langKey = ctx.getString(R.string.shared_options_select_language_key);
    String langDefault = ctx.getString(R.string.shared_options_select_language_default_value);
    String appLanguage = preferences.getString(langKey, langDefault);

    Locale locale = null;
    if (appLanguage.equals(langDefault)) {                
    locale = new Locale(Resources.getSystem().getConfiguration().locale.getLanguage());
    } else {
        String[] languageInfo = appLanguage.split("_");
        if (languageInfo.length > 1) {
            locale = new Locale(languageInfo[0], languageInfo[1]);
        } else {
            locale = new Locale(appLanguage);
        }
    }
    Locale.setDefault(locale);
    Configuration config = new Configuration();
    config.locale = locale;

    baseCtx.getResources().updateConfiguration(config, baseCtx.getResources().getDisplayMetrics());
}

Nessuna soluzione corretta

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top