Categories
Uncategorized

Preference element in xml and the click event

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:

<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:
    <Preference
    	android:key="my_key"
    	android:summary="my_summary"
     	android:title="my_title" >
    	<intent
    		android: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:
    Preference myPref = (Preference) findPreference("my_key");
    myPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
    	@Override
    	public boolean onPreferenceClick(Preference myPref) {
    		// your code
    		return true;
    	}
    });
    

2 replies on “Preference element in xml and the click event”

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.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.