GridView onclick not working with on touch
I have implemented a grid view in my application. for refreshing the grid i have given touch event to it. and in on click I do some stuff with that grid item. below is the code for gesture detector -
public class OnSwipeTouchListener implements OnTouchListener {
private final GestureDetector gestureDetector;
public OnSwipeTouchListener(Context ctx) {
gestureDetector = new GestureDetector(ctx, new GestureListener());
}
private final class GestureListener extends SimpleOnGestureListener {
private static final int SWIPE_THRESHOLD = 300;// make it 100 if down
// swipe is not working
private static final int SWIPE_VELOCITY_THRESHOLD = 100;
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
boolean result = false;
try {
float diffY = e2.getY() - e1.getY();
float diffX = e2.getX() - e1.getX();
if (Math.abs(diffX) > Math.abs(diffY)) {
if (Math.abs(diffX) > SWIPE_THRESHOLD
&& Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (diffX > 0) {
onSwipeRight();
} else {
onSwipeLeft();
}
}
} else {
if (Math.abs(diffY) > SWIPE_THRESHOLD
&& Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
if (diffY > 0) {
onSwipeBottom();
} else {
onSwipeTop();
}
}
}
} catch (Exception exception) {
exception.printStackTrace();
}
return result;
}
// @Override
// public boolean onSingleTapConfirmed(MotionEvent e) {
// onClick(); // my method
// return super.onSingleTapConfirmed(e);
// }
}
public void onSwipeRight() {
}
public void onSwipeLeft() {
}
public void onSwipeTop() {
}
public void onSwipeBottom() {
}
// public void onClick() {
// }
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return gestureDetector.onTouchEvent(event);
}
}
and below is the touch and click listeners on grid view -
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
gridView.setOnTouchListener(new OnSwipeTouchListener(
MidnightMainActivity.this) {
public void onSwipeBottom() {
gridView.startAnimation(slidedown);
inflateHomeLayout(MODE_REFRESH);
}
});
now touch is working but on click detects another item instead of clicked one. How can I solve this problem? Thanks in advance
Solution 1:
To respect StackOverflow question - answer flow, I place my answer here:
Why are you return true value in onDown function? Are you sure you handle this event? Try to return false.