简体   繁体   中英

How to add an OnTouchListener over a gridView?

So I have a layout that is made of GridView and I want to add an OnTouchListener to handle the event when the user swipes left or right, so I made a class that implements OnTouchListener it's called OnSwipeTouchListener and it's working really good but the problem is my gridView, the scroll is working fine and everything but when I click on an item it automatically chooses the first item in the row. any idea on how to fix this or another way to detect a left or right swipe and makes the gridview work fine, thanks.

PS: the gridView works fine when I remove the onTouchListener.

The OnSwipeTouchListner:

public class OnSwipeTouchListener implements OnTouchListener {

private final GestureDetector gestureDetector;

public OnSwipeTouchListener(Context context) {
    gestureDetector = new GestureDetector(context, new GestureListener());
}

public void onSwipeLeft() {
}

public void onSwipeRight() {
}

public boolean onTouch(View v, MotionEvent event) {
    return gestureDetector.onTouchEvent(event);
}

private final class GestureListener extends SimpleOnGestureListener {

    private static final int SWIPE_DISTANCE_THRESHOLD = 100;
    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) {
        float distanceX = e2.getX() - e1.getX();
        float distanceY = e2.getY() - e1.getY();
        if (Math.abs(distanceX) > Math.abs(distanceY) && Math.abs(distanceX) > SWIPE_DISTANCE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
            if (distanceX > 0)
                onSwipeRight();
            else
                onSwipeLeft();
            return true;
        }
        return false;
    }
}
}

calling it in the main activity:

gridView.setOnTouchListener(new OnSwipeTouchListener(this){
        public void onSwipeRight() {
        }
        public void onSwipeLeft() {
            }
    });

Try using setOnItemClickListener

gridView.setOnItemClickListener(

new OnItemClickListener(){
    public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {

    }
});
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM