How to attach GestureDetector to a ListPreference?

﹥>﹥吖頭↗ 提交于 2019-12-01 17:46:25

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):

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

As @TronicZomB suggested, this isn't directly possible.

You can work around this by creating your own ListPreference derived class, getting its view in the inherited onBindDialogView().

Remember however that the latter is tricky because onBindDialogView() is only called if onCreateDialogView() doesn't return null, and this can happen only if you create your own custom view for YourListPreference.

The recommended way to do this is to build a custom Preference.

Once you have done that, you have a reference to YourListPreference's view, which is mandatory for attaching GestureDetector because one of the steps requires setOnTouchListener() on the view.

I have set a GestrueDetector to a ScrollView using setOnTouchListener previously and searched for a similar method for ListPreference, however since the ListPreference does not contain such a method, I do not believe this will be possible.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!