简体   繁体   English

如何在gridView上添加OnTouchListener?

[英]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. 因此,我有一个由GridView构成的布局,我想添加一个OnTouchListener来处理用户向左或向右滑动时的事件,因此我制作了一个实现OnTouchListener的类,称为OnSwipeTouchListener ,它确实工作得很好,但是问题是我的在gridView上,滚动条工作正常,并且一切正常,但是当我单击某个项目时,它会自动选择该行中的第一个项目。 any idea on how to fix this or another way to detect a left or right swipe and makes the gridview work fine, thanks. 关于如何解决此问题的另一种方法,或通过其他方法检测左右滑动并使Gridview正常工作的想法,谢谢。

PS: the gridView works fine when I remove the onTouchListener. PS:当我删除onTouchListener时,gridView可以正常工作。

The OnSwipeTouchListner: 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 尝试使用setOnItemClickListener

gridView.setOnItemClickListener(

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

    }
});
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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