Android PrefernceFragment implements OnPreferenceClickListener never invoked on clicks

1.5k views Asked by At

I'm trying to implement OnPreferenceClickListener over PrefernceFragment and it seems like the onPreferenceClick() is never called.
I have another PrefernceFragment implementing OnSharedPreferenceChangeListener and it works just fine.
Is this a bug of the OS ? is the OnPreferenceClickListener not supposed to be supported for PrefernceFragment ?
If there is no need to register the fragment as listener as I read, then I really think my code is correct.

    public class myClass extends PreferenceFragment implements OnPreferenceClickListener {

    @Override
    public void onCreate(final Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(com.XX.ZZ.R.xml.YY);
    }

    @Override
    public boolean onPreferenceClick(Preference preference) {
        // never called.
    }
}
2

There are 2 answers

2
Nathan Walters On BEST ANSWER

PreferenceFragment doesn't have a onPreferenceClick() method. There is really no need to listen for click events since the Android fragment takes care of writing the preference values into memory. If you really need to watch for a click event, you can use findPreference(CharSequence key) to find each of the Preferences you want to watch and then call setOnPreferenceClickListener(this) on those.

1
Timuçin On

You must set preferenceClickListener on your preference.

public class myClass extends PreferenceFragment implements OnPreferenceClickListener {

    @Override
    public void onCreate(final Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(com.XX.ZZ.R.xml.YY);
        Preference preference = findPreference("myPreference");
        preference.setOnPreferenceClickListener(this);
    }

    @Override
    public boolean onPreferenceClick(Preference preference) {
        // never called.
    }

UPDATE:

If you want to set onPreferenceClickListener to all preferences, you can do it like this:

public class myClass extends PreferenceFragment implements OnPreferenceClickListener {

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.menu.main);

        Set<String> preferenceNames = getPreferenceManager().getSharedPreferences().getAll().keySet();
        for (String prefName : preferenceNames) {
            Preference preference = findPreference(prefName);
            preference.setOnPreferenceClickListener(this);
        }

    }

    @Override
    public boolean onPreferenceClick(Preference preference) {
        // or get preference.getKey() to select based on preference names
        switch (preference.getOrder()) {
        case 0:

            return true;
        case 1:

            return true;

        default:
            return false;
        }
    }
}