How to setOnTouchListener() on a ListPreference?

2019-02-22 10:29发布

问题:

Handling onTouchEvent on a view is straightforward as every view has the setOnTouchListener() method to do just that.

Alas, although ListPreference is a view, it isn't defined in a layout XML, and thus can't be accessed via findViewById(). So... I don't seem to figure out how to setOnTouchListener() for it.

My idea was to get a reference to it in PreferenceActivity's onCreate(), then getDialog().getCurrentFocus() but at that particular moment in time, it has no focus and not even a dialog (getDialog() returns null, confirmed).

Any idea how to work around this?

回答1:

Use registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) for the shared preferences, if you are interested in all the preferences, or .setOnPreferenceChangeListener(listener) if you only want to know the changes on one item. You will be notified when the preference is changed.