Matjaž
Matjaž

Reputation: 2115

PreferenceActivity do something when preference are changed

I have preference xml and following code:

public class MainActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener
{
    @SuppressWarnings("deprecation")
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        Toast.makeText(getApplicationContext(), "DO SOMETHING", Toast.LENGTH_LONG).show();
    }
}

I want to get notified over toast message, when one or more preferences are changed. I think upper code should work, but for some reason it doesn't.

I have for example CheckBoxPreference in my xml file. And when I check or uncheck CheckBox I want to be notified.

Upvotes: 0

Views: 297

Answers (2)

Nermeen
Nermeen

Reputation: 15973

You should register to listen to the shared preference changes:

@Override
    public void onPause() {
        super.onPause();

         getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
    }

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

        getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
    }

Upvotes: 1

Opiatefuchs
Opiatefuchs

Reputation: 9870

You have to set the listener like this for example:

       PreferenceManager.getDefaultSharedPreferences(this).
                                 registerOnSharedPreferenceChangeListener(this);

or, if You don´t use the default shared preferences, You have to get Your prefs and then register them:

       SharedPreferences preferences = getSharedPreferences("your_shared_prefs", Context.MODE_PRIVATE);
       preferences.registerOnSharedPreferenceChangeListener(this);

Upvotes: 1

Related Questions