Question

I have an app where the user can change its language.

Everything is working fine, with just this code on my MainActivity.onCreate():

String lang = PreferenceManager.getDefaultSharedPreferences(this).getString("languagePref", "default");
    Configuration config = getResources().getConfiguration();
    if( lang.equals("default") ) lang = Locale.getDefault().getLanguage();
    config.locale = new Locale(lang);
    getResources().updateConfiguration(config, getResources().getDisplayMetrics());

When I restart the app or navigate through activities it's still in the right language.

The only problem is on the PreferenceActivity screen. When the orientation changes, the PreferenceActivity title (and only it) changes to the default device language.

The prefs are still checked correctly, if I go back (closing the PreferenceActivity) the app is still on the right language, but the PreferenceActivity stays wrong until I restart the app.

I tried forcing the code above on the PreferenceActivity.onCreate() and altough debugging seems OK, the PrefenceActivity Title stays wrong.

Here's my PrefenceActivity code:

public class PreferencesActivity extends PreferenceActivity {

    @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
    }
}

This behavior doesn't happen on any other Activity :/

Locking the screen orientation is not an option.

Any thoughts?

Thanks.

Was it helpful?

Solution

OK, this fixed it for me.

@Override
protected void onSaveInstanceState(Bundle outState) {
    String lang = PreferenceManager.getDefaultSharedPreferences(this).getString("languagePref", "default");
    Configuration config = getResources().getConfiguration();
    if( lang.equals("default") ) lang = Locale.getDefault().getLanguage();
    config.locale = new Locale(lang);
    getResources().updateConfiguration(config, getResources().getDisplayMetrics());
    super.onSaveInstanceState(outState);
}

OTHER TIPS

I solved this problem using onConfigurationChanged(). In this method I'm saving preferred language again in Configuration object.

OnCreate method of activity is called when orientation is changes, so some property is again set by your code, look at your on oncreate method or lock your screen orientation.

You can lock your screen orientation to your activity by Using

android:screenOrientation="portrait"

or

android:screenOrientation="landscape"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top