截取回收者视图手势向右和向左滑动,android?

时间:2018-06-05 10:26:48

标签: android android-recyclerview ontouchlistener

我有一个recyclerView。当用户向右或向左滑动时执行某些操作。 请注意我不是要求回收者查看项目滑动,而是要求整个Recyclerview手势向左或向右。

为此,我扩展了View.OnTouchListener并试图获得如下手势

public class OnSwipeTouchListener implements View.OnTouchListener {

private final GestureDetector gestureDetector;

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

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

private final class GestureListener extends GestureDetector.SimpleOnGestureListener {

    private static final int SWIPE_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) {
        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();
                    }
                    result = true;
                }
            } /*else if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                if (diffY > 0) {
                    onSwipeBottom();
                } else {
                    onSwipeTop();
                }
                result = true;
            }*/
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return result;
    }
}

public void onSwipeRight() {
}

public void onSwipeLeft() {
}


/*public void onSwipeTop() {
}

public void onSwipeBottom() {
}
*/
}

然后将其用作

recyclerViewComponent.setOnTouchListener(new OnSwipeTouchListener(context){
        @Override
        public void onSwipeRight() {
            super.onSwipeRight();
        }

        @Override
        public void onSwipeLeft() {
            super.onSwipeLeft();
        }
    });

但我没有得到回调。这有什么问题?

1 个答案:

答案 0 :(得分:0)

根据官方Google doc,您在处理onInterceptTouchEvent时必须使用ViewGroupsRecyclerView扩展ViewGroup)。 因此,您必须扩展RecyclerView类才能覆盖其onTouchInterceptTouchEvent方法:

public class MyRecyclerView extends RecyclerView {

   @Override
   public boolean onInterceptTouchEvent(MotionEvent ev) {
       switch (MotionEventCompat.getActionMasked(ev)) {
          case MotionEvent.ACTION_MOVE: {
           [...]
          }
       }        
   }

}

然后,您还必须更改布局XML文件,以使用自定义RecyclerView MyRecyclerView

或者,您可以调整涉及第三方组件/库的解决方案,例如thisthis