4

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.

4

4 回答 4

3

好的,这为我解决了。

@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);
}
于 2013-11-18T20:38:32.883 回答
1

我使用onConfigurationChanged(). 在这种方法中,我再次将首选语言保存在配置对象中。

于 2017-01-11T07:52:57.747 回答
0

当方向改变时调用活动的 OnCreate 方法,因此您的代码再次设置了某些属性,查看您的 oncreate 方法或锁定您的屏幕方向。

于 2013-11-12T04:37:49.237 回答
-1

您可以通过使用将屏幕方向锁定到您的活动

android:screenOrientation="portrait"

或者

android:screenOrientation="landscape"
于 2013-11-12T03:43:31.107 回答