setOnPreferenceChangeListener is called when assigning listener to preference in Android

心已入冬 提交于 2019-12-25 05:00:43

问题


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


回答1:


You can achieve that this way. You need to register your listener in onResume and unregister in onPause. This way it won't get called when your activity is created as the initial changes to the preferences values have already taken place.

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
    }

}



回答2:


Change listeners fire even when the change happens programmatically, not exclusively as a result of user input (because user input ultimately leads to a programmatic change in the vaue, hence not differentiating).

The solution is to add the listeners after the view has been created and populated with the currently set preferences instead of adding them in onCreate.



来源:https://stackoverflow.com/questions/19747164/setonpreferencechangelistener-is-called-when-assigning-listener-to-preference-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!