Preference Change Listener

github: T06.05_PreferenceChangeListener

IMG_20170805_232957

// TODO (1) Implement OnSharedPreferenceChangeListener
public class VisualizerActivity extends AppCompatActivity implements OnSharedPreferenceChangeListener {
// TODO (2) Override the onSharedPreferenceChanged method and update the show bass preference
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    if(key.equals(getString(R.string.pref_show_bass_key))){
        mVisualizerView.setShowBass(sharedPreferences.getBoolean(key,getResources().getBoolean(R.bool.pref_show_bass_default)));
    }
}
// TODO (3) Register the listener
sharedPreferences.registerOnSharedPreferenceChangeListener(this);
//because this class already implements OnSharedPreferenceChangeListener so we can put 'this' here.
// TODO (4) Override onDestroy and unregister the listener
@Override
protected void onDestroy() {
    super.onDestroy();
    PreferenceManager.getDefaultSharedPreferences(this)
            .unregisterOnSharedPreferenceChangeListener(this);
}

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s