横向的recyclerView 嵌套了多个竖向的recyclerView,怎么让他们同时响应两根手指的滑动时间
时间: 2023-11-16 09:03:48 浏览: 69
要让横向的RecyclerView和嵌套的竖向的RecyclerView都能响应两根手指的滑动事件,可以在横向的RecyclerView的`onInterceptTouchEvent()`方法中判断如果是两根手指的滑动事件,则让竖向的RecyclerView也能接收到事件。
具体实现如下:
```
public class HorizontalRecyclerView extends RecyclerView {
private boolean mIsScrolling;
private int mActivePointerId = INVALID_POINTER_ID;
private float mLastTouchX;
private float mLastTouchY;
public HorizontalRecyclerView(Context context) {
super(context);
}
public HorizontalRecyclerView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public HorizontalRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent e) {
final int action = MotionEventCompat.getActionMasked(e);
switch (action) {
case MotionEvent.ACTION_DOWN:
mActivePointerId = e.getPointerId(0);
mLastTouchX = e.getX();
mLastTouchY = e.getY();
mIsScrolling = false;
break;
case MotionEvent.ACTION_POINTER_DOWN:
mIsScrolling = true;
break;
case MotionEvent.ACTION_MOVE:
if (!mIsScrolling) {
final int pointerIndex = e.findPointerIndex(mActivePointerId);
final float x = e.getX(pointerIndex);
final float y = e.getY(pointerIndex);
if (Math.abs(x - mLastTouchX) > Math.abs(y - mLastTouchY)) {
// 横向滑动
return super.onInterceptTouchEvent(e);
} else {
// 竖向滑动
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
if (child instanceof RecyclerView) {
RecyclerView verticalRecyclerView = (RecyclerView) child;
verticalRecyclerView.onInterceptTouchEvent(e);
}
}
return false;
}
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
mActivePointerId = INVALID_POINTER_ID;
mIsScrolling = false;
break;
}
return super.onInterceptTouchEvent(e);
}
}
```
这里重写了横向的RecyclerView的`onInterceptTouchEvent()`方法,当检测到手指数量为2时,就将事件传递给嵌套的竖向的RecyclerView处理。如果手指数量为1,则继续让横向的RecyclerView自己处理事件。
阅读全文