4

There are only so many types of Preference types we can set in PreferenceActivity. I am trying to run a specific function once a certain preference is clicked. Is there a way to override a preferenceScreen or editText onClick?

  • That's what the PrefrenceActivity is for. And btw I think you mean method not function right? – Ahmad Nov 21 '12 at 23:53

1 Answers1

5

Yes you can. Here's a simple example of how to get the preference reference and execute custom code on a click event.

public class ActivityPreferences extends PreferenceActivity
{
    protected void onCreate( Bundle savedInstanceState )
    {
        super.onCreate( savedInstanceState );
        addPreferencesFromResource( R.xml.preferences );

        Preference myPref = findPreference( "MY_PREF" );
        myPref.setOnPreferenceClickListener( new OnPreferenceClickListener()
        {
            public boolean onPreferenceClick( Preference pref )
            {
                  // Run your custom method
            }
        } );
    }
}
Robert Estivill
  • 12,369
  • 8
  • 43
  • 64
  • Ahmad, yes - method sorry. Robert, what type of preference does "MY_PREF" have to be so that there are no other ex. Check boxes being checked or text field popping up afterward? Thanks – Morgan Culbertson Nov 22 '12 at 03:40
  • MY_PREF is the preference key. myPref is of the top level Preference type. If you want, you can cast it to whatever subclass of Preference you are using: CheckboxPreference myPref = (CheckboxPreference)findPreference( "MY_PREF" ); – Robert Estivill Nov 22 '12 at 03:45
  • But is there a specific subclass that does not have a check box that will turn on and off etc. One that will function primarily as an onClick. One that does not do anything else once clicked. – Morgan Culbertson Nov 22 '12 at 03:58
  • Yes, the top level Preference. – Robert Estivill Nov 22 '12 at 13:14
  • @MorganCulbertson please flag the answer as correct – Robert Estivill May 15 '17 at 21:15