2018+ UPDATE
Today, the findPreference
method is depricated. So, to achieve this, just override the onPreferenceTreeClick
method in your Preference fragment. For example:
public class MySettingsFragment extends PreferenceFragment {
@Override
public boolean onPreferenceTreeClick (PreferenceScreen preferenceScreen,
Preference preference)
{
String key = preference.getKey();
if(key.equals("someKey")){
// do your work
return true;
}
return false;
}
}
Furthermore, if you need to handle a click inside particular preference element (e.g. ListPreference
), you should register the setOnPreferenceChangeListener
inside the onCreate
method of the MySettingsFragment
:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
// register listener
final Preference prefList = findPreference("key");
prefList.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object value) {
System.out.println("Selected: " + value);
return true;
}
});
}
onPostCreate
wont work because it is too early(Nullpointer-Exception). Any help is appreciated – Twoply