Pergunta

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

Foi útil?

Solução

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
    }

}

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top