tags:

views:

87

answers:

1

Hello, I have managed to create a menu using the xml and a class that extends PreferenceActivity and implements OnSharedPreferenceChangeListener, now I would like to be notified everytime the user changes a value from preferences (e.g. when a user changes the username). To do that I have registered my class using the method registerOnSharedPreferenceChangeListener.

and implemented onSharedPreferenceChanged method.

this enable my application to be notified for a change but how can I actually change the value?

is there any good tutorial about this because I haven't found any.

thanks in advanced maxsap

A: 

If I understand your question correctly, this is how I perform the change:

public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) 
{
    // Get a link to your preferences:
 SharedPreferences s = getSharedPreferences("MY_PREFS", 0);

    // Create a editor to edit the preferences:
    SharedPreferences.Editor editor = s.edit();

    // Let's do something a preference value changes
    if (key.equals("hintsPreference")) 
    {
        // Create a reference to the checkbox (in this case):
        CheckBoxPreference mHints = (CheckBoxPreference)getPreferenceScreen().findPreference("hintsPreference");
        //Lets change the summary so the user knows what will happen using a one line IF statement:
     mHints.setSummary(mHints.isChecked() ? "Hints will popup." : "No hints will popup.");
        // Lets store the new preference:
     editor.putBoolean("hintsPreference", mHints.isChecked());
    }
    /**
     * You could perform several else if statements, or probably better use a switch block.
     */

    // Save the results:
    editor.commit();
}

My XML entry would look something like:

<CheckBoxPreference android:key="hintsPreference" android:title="Show Helpful Hints:" />

This isn't tested, I have stripped alot out to make it alot simpler, but hopefully it will be enough to help.

Forexample, in your onCreate Method you could do something like:

    // Link to your checkbox:
    CheckBoxPreference mHints = (CheckBoxPreference)getPreferenceScreen().findPreference("hintsPreference");
    // Set the summary based on the one line IF statement:
    mHints.setSummary(s.getBoolean("hintsPreference", true) ? "Hints will popup." : "No hints will popup.");
    // Set the box as either ticked or unticked:
    mHints.setChecked(s.getBoolean("hintsPreference", true));
Scoobler