Search code examples
androidlistpreferencegesturedetector

How to attach GestureDetector to a ListPreference?


The challenge of attaching a GestureDetector to a ListPreference is 2-fold:

  1. Getting a handle to a ListPreference that's only defined in a preferences.xml (i.e. not instantiated in Java code).
  2. ListPreference is neither a View nor Activity subclass.

Is it possible at all to attach a GestureDetector to a ListPreference?

If so, how would one go about this? Where would I write the code to instantiate GestureDetector and implement the listener?


Solution

  • Unless I didn't quite catch the question correctly, the answer is probably simpler than you might think. The source code for ListPreferece teaches that it's little more than a wrapper around an AlertDialog that displays its various options in a ListView. Now, AlertDialog actually allows you to get a handle on the ListView it wraps, which is probably all you need.

    In one of the comments you indicated that, at this stage, all you're interested in is detecting a long-press on any item in the list. So rather than answering that by attaching a GestureDetector, I'll simply use an OnItemLongClickListener.

    public class ListPreferenceActivity extends PreferenceActivity implements OnPreferenceClickListener {
    
        private ListPreference mListPreference;
    
        @Override protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            addPreferencesFromResource(R.xml.list_prefs);
    
            mListPreference = (ListPreference) findPreference("pref_list");
            mListPreference.setOnPreferenceClickListener(this);
        }
    
        @Override
        public boolean onPreferenceClick(Preference preference) {
            AlertDialog dialog = (AlertDialog) mListPreference.getDialog();
            dialog.getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
                    Toast.makeText(getApplicationContext(), "Long click on index " + position + ": " 
                            + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
                    return false;
                }
            });
            return false;
        }
    
    }
    

    The result (which the toast in the long-click displaying):

    enter image description here

    With a reference to the ListView, you could also attach an OnTouchListener, GestureDetector etc. Up to you to go from here.