If you have an EditTextPreference tag in a xml file you can catch the click event implementing OnSharedPreferenceChangeListener but it doesn’t work if you have a Preference tag in the xml file.
Consider the following code inside a xml file for the preferences:
1 2 3 4 5 |
<Preference android:key="my_key" android:summary="my_summary" android:title="my_title" > </Preference> |
You can catch the click event using one of these ways:
- implementing an intent in the xml file, for example, in order to open a web page the code is:
12345678<Preferenceandroid:key="my_key"android:summary="my_summary"android:title="my_title" ><intentandroid:action="android.intent.action.VIEW"android:data="http://www.example.com" /></Preference> - implementing a Preference.OnPreferenceClickListener listener, for example, in your activity or fragment add the following:
12345678Preference myPref = (Preference) findPreference("my_key");myPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {@Overridepublic boolean onPreferenceClick(Preference myPref) {// your codereturn true;}});
2 replies on “Preference element in xml and the click event”
L’istruzione findPreference(“a_key”) è stata deprecata…
L’esempio che ho riportato è parte di un progetto in cui findPreference è un metodo di PreferenceFragment dove non è deprecato, ma effettivamente ho verificato che in altre classi come PreferenceActivity è deprecato con la motivazione: “This method was deprecated in API level 11. This function is not relevant for a modern fragment-based PreferenceActivity.“