RecyclerView横向和竖向滑动冲突

本文介绍了一个扩展自RecyclerView的自定义视图BetterRecyclerView,该组件优化了多点触控的手势识别逻辑,增强了滑动响应机制,并提供了更精细的触摸事件处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class BetterRecyclerView extends RecyclerView {

    private int touchSlop;
    private Context mContext;
    private int INVALID_POINTER = -1;
    private int scrollPointerId = INVALID_POINTER;

    private int initialTouchX;
    private int initialTouchY;


    private final static String TAG = "BetterRecyclerView";

    public BetterRecyclerView(Context context) {
//        super(context);
        this(context, null);
    }

    public BetterRecyclerView(Context context, @Nullable AttributeSet attrs) {
//        super(context, attrs);
        this(context, attrs, 0);
    }

    public BetterRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        ViewConfiguration vc = ViewConfiguration.get(context);
        touchSlop =vc.getScaledEdgeSlop() ;
        mContext =context ;

    }

    @Override
    public void setScrollingTouchSlop(int slopConstant) {
        super.setScrollingTouchSlop(slopConstant);
        ViewConfiguration vc = ViewConfiguration.get(mContext);
        switch (slopConstant) {
            case TOUCH_SLOP_DEFAULT:
                touchSlop = vc.getScaledTouchSlop();
                break;
            case TOUCH_SLOP_PAGING:
                touchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(vc);
                break;

        }

    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent e) {

        if (e==null){
            return  false ;
        }
        int action = MotionEventCompat.getActionMasked(e);
        int actionIndex = MotionEventCompat.getActionIndex(e);

        switch (action){
            case MotionEvent.ACTION_DOWN :
                scrollPointerId = MotionEventCompat.getPointerId(e, 0);
                initialTouchX = Math.round(e.getX() + 0.5f);
                initialTouchY = Math.round(e.getY() + 0.5f);

                return super.onInterceptTouchEvent(e);

            case MotionEvent.ACTION_POINTER_DOWN:

                scrollPointerId = MotionEventCompat.getPointerId(e, actionIndex);
                initialTouchX = Math.round(MotionEventCompat.getX(e, actionIndex) + 0.5f);
                initialTouchY = Math.round(MotionEventCompat.getY(e, actionIndex) + 0.5f);

                return super.onInterceptTouchEvent(e);
            case MotionEvent.ACTION_MOVE:
                final int index =e.findPointerIndex(scrollPointerId);


                if ( index<0){
                    return  false ;
                }

                int x = Math.round(MotionEventCompat.getX(e, index) + 0.5f);
                int y = Math.round(MotionEventCompat.getY(e,index)+0.5f);

                if (getScrollState()!=SCROLL_STATE_DRAGGING){

                    int dx =x-initialTouchX ;

                    int  dy = y-initialTouchY ;
                    boolean startScroll = false;
                    if ((getLayoutManager().canScrollHorizontally()&&Math.abs(dx)>touchSlop)&&(getLayoutManager().canScrollVertically()||Math.abs(dx)>Math.abs((dy)))){
                           startScroll = true ;
                    }

                    if ((getLayoutManager().canScrollHorizontally()&&Math.abs(dy)>touchSlop)&&(getLayoutManager().canScrollHorizontally()||Math.abs(dy)>Math.abs((dx)))){

                        startScroll = true ;

                    }
                    return  startScroll && super.onInterceptTouchEvent(e);
                }
                return super.onInterceptTouchEvent(e);
        }
        return super.onInterceptTouchEvent(e);
    }
}
多点触摸手势 当多个pointer同时触摸屏幕,系统会生成如下事件:

        ACTION_DOWN—For the first pointer that touches the screen. This starts the gesture. The pointer data for this pointer is always at index 0 in the MotionEvent.
        ACTION_POINTER_DOWN—For extra pointers that enter the screen beyond the first. The pointer data for this pointer is at the index returned by getActionIndex().
        ACTION_MOVE—A change has happened during a press gesture.
        ACTION_POINTER_UP—Sent when a non-primary pointer goes up.
        ACTION_UP—Sent when the last pointer leaves the screen.
          你可以依靠每一个pointer的index和ID来追踪每一个pointer:

          Index:MotionEvent会把每一个pointer的信息放在一个数组里,index即是这个数组索引。大多数你用的MotionEvent方法是以这个index作为参数的。

          ID:每一个pointer还有一个ID映射,在touch事件中保持恒定一致(persistent),这样就可以在整个手势中跟踪一个单独的pointer。



          pointer在一个motion event中出现的顺序是未定的,所以pointer的index在不同的事件中是可变的,但是只要pointer保持active,它的ID是保持不变的。

          通过getPointerId()获得ID,这样就可以在多个motion event中追踪pointer。然后对于连续的motion event,可以使用findPointerIndex()方法来获得指定ID的pointer在当前事件中的index。

          比如:

        复制代码
private int mActivePointerId;

public boolean onTouchEvent(MotionEvent event) {
        ....
        // Get the pointer ID
        mActivePointerId = event.getPointerId(0);

        // ... Many touch events later...

        // Use the pointer ID to find the index of the active pointer 
        // and fetch its position
        int pointerIndex = event.findPointerIndex(mActivePointerId);
        // Get the pointer's current position
        float x = event.getX(pointerIndex);
        float y = event.getY(pointerIndex);
        }

### 解决 Android RecyclerView 嵌套布局中的滑动冲突 在处理 `RecyclerView` 的嵌套布局时,确实会遇到滑动冲突的问题。这主要是由于多个可滚动视图争夺触摸事件的控制权所引起的。 #### 方法一:自定义父级 `RecyclerView` 为了防止子项内的滑动手势被误判为外部容器的手势,可以创建一个继承于 `RecyclerView` 的类,并重写其 `onInterceptTouchEvent()` 方法[^2]: ```java public class ParentRecyclerView extends RecyclerView { public ParentRecyclerView(@NonNull Context context) { super(context); } @Override public boolean onInterceptTouchEvent(MotionEvent e) { // 获取当前手势动作类型 int action = MotionEventCompat.getActionMasked(e); switch (action){ case MotionEvent.ACTION_DOWN: // 当按下屏幕时允许所有父控件拦截事件 getParent().requestDisallowInterceptTouchEvent(false); break; case MotionEvent.ACTION_MOVE: // 如果检测到移动,则通知父控件不拦截此后的触碰事件 getParent().requestDisallowInterceptTouchEvent(true); break; case MotionEvent.ACTION_UP: // 抬起手指后恢复默认行为 getParent().requestDisallowInterceptTouchEvent(false); break; } return super.onInterceptTouchEvent(e); } } ``` 这种方法能够有效地让内部的 `RecyclerView` 获得优先响应的机会,在水平方向上实现流畅的滑动效果。 #### 方法二:设置 `OnTouchListener` 另一种方式是在具体的子 `RecyclerView` 上添加 `OnTouchListener` 来阻止父层捕获特定条件下的触摸操作[^4]: ```java holder.smallRecyclerView.setOnTouchListener((v, event) -> { if(event.getAction() == MotionEvent.ACTION_MOVE){ v.getParent().requestDisallowInterceptTouchEvent(true); }else{ v.getParent().requestDisallowInterceptTouchEvent(false); } return false; // 返回false表示继续传递给下一层组件处理 }); ``` 这段代码会在用户尝试垂直或水平拖拽子 `RecyclerView` 内容的时候告知它的上级不允许截断这些交互请求,从而确保了子列表能正常工作而不受外界干扰。 以上两种方案都可以很好地应对大多数情况下由多层滚动结构带来的挑战。具体采用哪种取决于实际应用场景个人偏好。 对于更复杂的场景比如 `CoordinatorLayout + AppBarLayout + ViewPager2` 组合中再加入横向滑动的 `RecyclerView` ,则可能还需要额外考虑不同部件之间的协调机制以及它们各自的特性[^1]。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值