How to add OnTouchListener to listview items?

Th0rndike picture Th0rndike · Mar 21, 2012 · Viewed 10.7k times · Source

I'm coding a simple android application which contains a list, populated with a SimpleCursorAdapter.

private void populateList() {
    c = this.cDAO.fetchAllContacts();
    startManagingCursor(c);

    String[] from = new String[]{ContactsDAO.KEY_NOME};

    int[] to = new int[]{R.id.nome1};

    SimpleCursorAdapter notes = 
        new MyListAdapter(this, R.layout.list_row, c, from, to, activitySwipeDetector);
    setListAdapter(notes);

}

The xml for the list and list_row:

<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/listaBottom"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#B5E61D"
    >


<ListView android:id="@+id/android:list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#B5E61D"
        android:divider="#80FFFF"
        android:dividerHeight=".5dp"

        />
</LinearLayout>

<?xml version="1.0" encoding="utf-8"?>

<TextView android:id="@+id/nome1"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" 
    android:textSize="30dp"
    android:textColor="#5289DC"
    /> 

Also, I have set an OnTouchListener on the listview to listen to swipe and click events, which is working correctly, except for the fact that it does not listen to events that happen in any of the items in the list. Doing some research I found that I need to extend the SimpleCursorAdapter to add the listener to all the items. Here's my extended class:

public class MyListAdapter extends SimpleCursorAdapter {
    ActivitySwipeDetector asd;
    public MyListAdapter(Context context, int layout, Cursor c, String[] from, int[] to, ActivitySwipeDetector asd) {
        super(context, layout, c, from, to);
        this.asd = asd;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        View view = super.getView(position, convertView, parent);
        TextView row = (TextView)view.findViewById(R.id.nome1);
        row.setOnTouchListener(asd);
        return view;
    }
}

This is not working. Does anyone have an idea of how to make it work?

EDIT: Just to clarify, all I want is that the gestures done on the list items (swipe left, swipe right, click) are recognized. So far, if I do a gesture in the empty part of the list (under the items) the listener catches the event, but if I do it on an item, the swipe is not recognized.

Answer

Th0rndike picture Th0rndike · Mar 22, 2012

The code i posted in the question works fine. The problem was in my touch listener, which didn't do the actions requested by gesture events.