开发者

How to detect if changes were made in the preferences?

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 helps...

http://developer.android.com/reference/android/content/SharedPreferences.OnSharedPreferenceChangeListen开发者_如何学编程er.html

Other related post: SharedPreferences.onSharedPreferenceChangeListener not being called consistently


public class PreferenceClass extends PreferenceActivity {

    OnSharedPreferenceChangeListener listener;

    public void onCreate(Bundle savedInstanceState) {
        SharedPreferences prefs = this.getSharedPreferences("settings", 0);
        listener = new SharedPreferences.OnSharedPreferenceChangeListener() {

            public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
                int flag = 1;
            }
        };
        prefs.registerOnSharedPreferenceChangeListener(listener);
        super.onCreate(null);
        addPreferencesFromResource(R.xml.settings);
    }
}


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().


In your PreferenceActivity class, implement the SharedPreferences.OnSharedPreferenceChangeListener interface. Add the required onSharedPreferenceChanged method to your class and register it in the onCreate.

See sample code here:

public class MyPreferences extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.fw_preferences); //deprecated
        PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        // handle the preference change here
    }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜