其他分享
首页 > 其他分享> > android – 如何在触摸/滑动/抛出其行时阻止ListView滚动?

android – 如何在触摸/滑动/抛出其行时阻止ListView滚动?

作者:互联网

我需要停止ListView以响应用户手势,如果这些手势是在某个特定的ListView行中进行的 – 如何做到这一点?目标ListView的行视图具有onTouchListener设置,由于ListView向上/向下滚动,我无法识别滑动/翻转.因此,如果我向上或向下移动手指 – ListView会截取并向相应方向滚动.所以我需要以某种方式来统治它,如果Y-coord超过一些量 – 让ListView滚动,如果不是 – 将手势识别为fling / swipe. OnTouchListener是

private int SWIPE_MIN_DISTANCE = 1;
private int SWIPE_MAX_OFF_PATH = 300;

final OnTouchListener flingSwipeListener =  new OnTouchListener() {
    float touchX;
    float touchY;
    @Override
    public boolean onTouch(final View view, final MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN)
        {
            touchX = event.getX();
            touchY = event.getY();
        }
        else if (event.getAction() == MotionEvent.ACTION_UP)
        {                   
        if (Math.abs(touchY - event.getY()) > SWIPE_MAX_OFF_PATH)
                    return false;
            // right to left swipe
            else if (touchX - event.getX() > SWIPE_MIN_DISTANCE){
                    Log.i("flingSwipe","right to left swipe");
            } 
            // left to right swipe
            else if (event.getX() - touchX > SWIPE_MIN_DISTANCE){
                    Log.i("flingSwipe","left to right swipe");
            }
        }
        return true;

    }
};

此onTouchListner设置为一个特定行.我需要冻结ListView,而onTouchListener识别手势,但如果失败,我需要将MotionEvent发送到ListView.

解决方法:

如果要在检测到任何水平滚动(滑动)时禁用ListView的垂直滚动,请使用以下解决方案 – 覆盖自定义ListView类中的onTouchEvent,并将动作MotionEvent.ACTION_MOVE替换为MotionEvent.ACTION_CANCEL:

public class ListView2 extends ListView
{
    private enum ScrollDirection
    {
        Horizontal,
        Vertical
    }

    private final int touchSlop;

    private float downX = 0;
    private float downY = 0;

    private ScrollDirection scrollDirection;

    public ListView2(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        touchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev)
    {
        switch (ev.getActionMasked())
        {
            case MotionEvent.ACTION_MOVE:
                if (scrollDirection == null)
                {
                    if (Math.abs(downX - ev.getX()) > touchSlop) scrollDirection = ScrollDirection.Horizontal;
                    else if (Math.abs(downY - ev.getY()) > touchSlop) scrollDirection = ScrollDirection.Vertical;
                }
                if (scrollDirection == ScrollDirection.Horizontal) ev.setAction(MotionEvent.ACTION_CANCEL);
                break;

            case MotionEvent.ACTION_DOWN:
                scrollDirection = null;
                downX = ev.getX();
                downY = ev.getY();
                break;

        }
        return super.onTouchEvent(ev);
    }
}

当然,您可以检查逻辑是否禁用垂直滚动更复杂.

标签:android,listview,gesture
来源: https://codeday.me/bug/20190709/1409065.html