Sebek Sebek - 2 months ago 22
Android Question

Swipe detection on Listview not working for custom Listview Adapter

I implemented a gesture detector to find out when the user will fling my listview (and when the last element of the list is in view) so that I may add more data to the list. The list has a custom adapter that I've built. Each row has a few textviews in it and an image button. I was using the imagebutton (which is an arrow) with a click listener in my adapter to open another activity related to the pressed row.

Management wants the user to be able to click anywhere on the row in order to activate it. So:

@Override
public View getView(final int position, View convertView, ViewGroup parent)
{
View v = convertView;
final ViewHolder viewHolder;
.....
//viewHolder.ibShipmentDetails.setOnClickListener(new OnClickListener()
v.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View view)
{
....
}
}


But now, my fling detector won't work correctly. Sometimes it responds and afterwards works correctly; restart the activity, again it doesn't work.

Here is my gesture detector:

class MyGestureDetector extends GestureDetector.SimpleOnGestureListener
{

@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {


if((e1.getY() - e2.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY))
{


if(!loading && ((totalItemCount - visibleItemCount) <= firstVisibleItem))
{
if(allTabSelected)
{
allPageNo++;
}
else
{
openPageNo++;
}

new GetShipmentPreviews().execute(1);
}
}
}


And in my activity:

gestureDetector = new GestureDetector(this, new MyGestureDetector());
gestureListener = new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event)
{
return gestureDetector.onTouchEvent(event);
}
};

listView.setOnTouchListener(gestureListener);


What should I do to keep
v.setOnClickListener
and the onFling() command intact?

Answer

Turns out my MotionEvents from onFling are null. This apparently happens because the event gets somehow "eaten" by the onClickListener from my custom adapter.

I got the solution from this answer : http://stackoverflow.com/a/7159738/1688731

I added the following code to my Activity class:

@Override
public boolean dispatchTouchEvent(MotionEvent ev)
{
  super.dispatchTouchEvent(ev);
  return gestureScanner.onTouchEvent(ev);
}