How to detect if changes were made in the preferences?

后端 未结 2 959
孤街浪徒
孤街浪徒 2020-12-01 02:38

I have a class that extends PreferenceActivity and shows the preference screen of my app. Is it possible to check if any changes were made to the preferences?

This h

2条回答
  •  庸人自扰
    2020-12-01 03:08

    Do

    SharedPreferences.OnSharedPreferenceChangeListener spChanged = new
                               SharedPreferences.OnSharedPreferenceChangeListener() {
                @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
                String key) {
            // your stuff here
        }
    };
    

    In your PreferenceActivity, ie make it a member of your PreferenceActivity class and then do registerOnSharedPreferenceChangeListener(spChanged) in the PreferenceActivity.onCreate() method.

    That's what I do and I never have a problem.

    Else it's your conditional checking in the listener that is at fault. Post the code.

    EDIT:

    From the code you posted, you should make prefs a class member variable so it has a global scope.

    And do prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); instead of getSharedPreferences because you haven't created that file.

    To create a file you need to use PreferenceManager. To get a PreferenceManager, use Activity.getPreferenceManager().

提交回复
热议问题