当ViewPager2嵌套RecyclerView上下滑动的事件会被RecyclerView分发下去到ViewPager2,这样就会造成卡顿。解决办法就是重写RecyclerView的dispatchTouchEvent函数,将上滑事件拦截下来选择不分发给下一层的View自己处理。
Java代码
// 用于标记滑动的坐标
private int downX= 0;
private int downY= 0;
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
int x = (int) ev.getX();
int y = (int) ev.getY();
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN: {
getParent().requestDisallowInterceptTouchEvent(true);
break;
}
case MotionEvent.ACTION_MOVE: {
int deltaX = x - downX;
int deltaY = y - downX;
//左右滑动
if (Math.abs(deltaX) > Math.abs(deltaY)) {
getParent().requestDisallowInterceptTouchEvent(false);
}
break;
}
case MotionEvent.ACTION_UP: {
getParent().requestDisallowInterceptTouchEvent(false);
break;
}
}
//赋值
downX= x;
downX= y;
return super.dispatchTouchEvent(ev);
}
kotlin代码
var downX: Int = 0
var downY = 0
override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
val x = ev.x.toInt()
val y = ev.y.toInt()
when (ev.action) {
MotionEvent.ACTION_DOWN -> {
//拦截
parent.requestDisallowInterceptTouchEvent(true)
}
MotionEvent.ACTION_MOVE -> {
val deltaX: Int = x - downX
val deltaY: Int = y - downX
if (Math.abs(deltaX) > Math.abs(deltaY)) {
parent.requestDisallowInterceptTouchEvent(false)
}
}
MotionEvent.ACTION_UP -> {
parent.requestDisallowInterceptTouchEvent(false)
}
}
downX= x
downX= y
return super.dispatchTouchEvent(ev)
}
点个赞呗