我已经在ViewPager的Fragment中实现了拖动以关闭和缩放视图。现在,它的滑动并不平滑,因为ViewPager和Fragment中的视图的触摸彼此冲突。因此,我编写了一个CustomViewPager类来覆盖' onInterceptTouchEvent '方法,这样我可以检测到它是否为水平滑动并且片段视图尚未缩放或拖动,则ViewPager应该使用触摸以避免冲突并进行滑动流畅。但是我面临的问题是,单击按钮也无法获得操作,因为ViewPager不会将触摸传递给它们,如果我没有在ViewPager中拦截触摸,则ViewPager和片段会发生冲突。我该如何允许孩子点击并消耗其他事件,例如ACTION_MOVE,直到我希望它传递给孩子。
CustomViewPager:
public class DemoViewPager extends ViewPager {
private final int THRESHOLD = ScreenUtils.dpToPx(20);
float diffX, diffY;
private float initialXValue;
private float initialYValue;
private MotionEventListener motionEventListener;
public DemoViewPager(@NonNull Context context) {
super(context);
}
public DemoViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
initialXValue = ev.getX();
initialYValue = ev.getY();
return true;
// break;
case MotionEvent.ACTION_MOVE:
diffX = ev.getX() - initialXValue;
diffY = ev.getY() - initialYValue;
boolean isHorizontalSwipe = Math.abs(diffY) < THRESHOLD;
boolean isDraggable = motionEventListener != null && (motionEventListener.isDragging() || motionEventListener.isZoomed());
if (!isHorizontalSwipe || isDraggable) {
return true;
}
// return true;
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
break;
//return true;
}
return super.onInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
initialXValue = ev.getX();
initialYValue = ev.getY();
if (motionEventListener != null)
motionEventListener.onMotionEventReceived(ev);
break;
case MotionEvent.ACTION_MOVE:
diffX = ev.getX() - initialXValue;
diffY = ev.getY() - initialYValue;
boolean isHorizontalSwipe = Math.abs(diffY) < THRESHOLD;
boolean isDraggable = motionEventListener != null && (motionEventListener.isDragging() || motionEventListener.isZoomed());
if (!isHorizontalSwipe || isDraggable) {
if (motionEventListener != null)
motionEventListener.onMotionEventReceived(ev);
if (isDraggable)
return false;
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if (motionEventListener != null)
motionEventListener.onMotionEventReceived(ev);
break;
}
return super.onTouchEvent(ev);
}
public void setMotionEventListener(MotionEventListener motionEventListener) {
this.motionEventListener = motionEventListener;
}
public interface MotionEventListener {
void onMotionEventReceived(MotionEvent motionEvent);
boolean isDragging();
boolean isZoomed();
}
}