SharedPreferences.onSharedPreferenceChangeListener not being called consistently

前端 未结 8 1094
终归单人心
终归单人心 2020-11-22 06:47

I\'m registering a preference change listener like this (in the onCreate() of my main activity):

SharedPreferences prefs = PreferenceManager.get         


        
8条回答
  •  渐次进展
    2020-11-22 07:36

    As this is the most detailed page for the topic I want to add my 50ct.

    I had the problem that OnSharedPreferenceChangeListener wasn't called. My SharedPreferences are retrieved at the start of the main Activity by:

    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    

    My PreferenceActivity code is short and does nothing except showing the preferences:

    public class Preferences extends PreferenceActivity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // load the XML preferences file
            addPreferencesFromResource(R.xml.preferences);
        }
    }
    

    Every time the menu button is pressed I create the PreferenceActivity from the main Activity:

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        //start Preference activity to show preferences on screen
        startActivity(new Intent(this, Preferences.class));
        //hook into sharedPreferences. THIS NEEDS TO BE DONE AFTER CREATING THE ACTIVITY!!!
        prefs.registerOnSharedPreferenceChangeListener(this);
        return false;
    }
    

    Note that registering the OnSharedPreferenceChangeListener needs to be done AFTER creating the PreferenceActivity in this case, else the Handler in the main Activity won't be called!!! It took me some sweet time to realize that...

提交回复
热议问题