0

In my preferences screen I set listeners to some preferences on onCreate().
But I've noticed the listener is called every time the preference is loaded (probably on the onCreate()).
Is there a way to prevent this ?
I want of course the listener to be called only when the preference value in the given key is changed.

Thanks

4

2 回答 2

1

即使更改以编程方式发生,更改侦听器也会触发,而不仅仅是用户输入的结果(因为用户输入最终会导致 vaue 的编程更改,因此不会区分)。

解决方案是在创建视图并使用当前设置的首选项填充视图后添加侦听器,而不是将它们添加到onCreate.

于 2013-11-02T21:53:26.847 回答
1

你可以通过这种方式实现。您需要在 中注册您的听众并在中onResume注销onPause。这样,当您的活动被创建时,它不会被调用,因为首选项值的初始更改已经发生。

public class SettingsActivity extends PreferenceActivity
    implements OnSharedPreferenceChangeListener {

    @Override
    protected void onResume() {
        super.onResume();

        // Set up a listener whenever a key changes
        getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        // Unregister the listener whenever a key changes
        getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
    }

    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
        String key) {
        // Let's do something a preference value changes
    }

}
于 2013-11-02T21:54:32.130 回答