SharedPreference Change Listener and custom preference

887 views Asked by At

I have those preference:

<xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<CheckBoxPreference
    android:key="pk1"
    android:title="@string/pt1"
    android:summary="@string/pt1s"
    android:defaultValue="false" />
<CheckBoxPreference
    android:key="pk2"
    android:title="@string/pt2"        
    android:defaultValue="false" />
<ListPreference 
    android:key="pk3"
    android:title="@string/pt3"
    android:dialogTitle="@string/pt3"
    android:entries="@array/fontsi"
    android:entryValues="@array/fontsiv"
    android:defaultValue="0" />     
<Preference
android:key="pkb"
android:title="@string/ptb" />
</PreferenceScreen>

And the settings activity:

public class SettingsActivity extends PreferenceActivity {
SharedPreferences.OnSharedPreferenceChangeListener lst;
SharedPreferences prf;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);
    prf = getPreferenceScreen().getSharedPreferences();
    lst = new SharedPreferences.OnSharedPreferenceChangeListener() {
    public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
    Log.i("SettingsActivity","!any preference changen!");
    if (key.equals("pk1")) { Log.i("SettingsActivity","!pref PK1 called!"); }                                            }  
    else if (key.equals("pkb")) { Log.i("SettingsActivity","!pref PKB called!"); }            
    prf.registerOnSharedPreferenceChangeListener(lst);
}

@Override
protected void onResume() {
    super.onResume();
    prf.registerOnSharedPreferenceChangeListener(lst); }

@Override
protected void onPause() {
    super.onPause();
    prf.unregisterOnSharedPreferenceChangeListener(lst); }
...    
}

The listener works with all the preferences but e custom preference (the last one, pkb as key)! That i want to use as a back button. Anybody knows why ?

1

There are 1 answers

1
Simas On BEST ANSWER

Obviously your preference doesn't change any preferences.

Since it doesn't do anything, OnSharedPreferenceChangeListener ignores it.

A possible solution would be to set a clickListener to it like this:

findPreference("pkb").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
    @Override
    public boolean onPreferenceClick(Preference preference) {
        Log.i("SettingsActivity", "!pref PKB called!");
        return false;
    }
});