您还错过了一个事件:onInterceptTouchEvent。它必须包含与 onTouchEvent 相同的逻辑。
我的完整解决方案基于此 答案。它将允许您在需要的任何时间启用/禁用任何方向的分页。
1.创建枚举
public enum SwipeDirection {
ALL, LEFT, RIGHT, NONE ;
}
2.扩展ViewPager(Java)
public class CustomViewPager extends ViewPager {
private float initialXValue;
private SwipeDirection direction;
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
this.direction = SwipeDirection.ALL;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (this.isSwipeAllowed(event)) {
return super.onTouchEvent(event);
}
return false;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (this.isSwipeAllowed(event)) {
return super.onInterceptTouchEvent(event);
}
return false;
}
private boolean isSwipeAllowed(MotionEvent event) {
if(this.direction == SwipeDirection.ALL) return true;
if(direction == SwipeDirection.NONE )//disable any swipe
return false;
if(event.getAction()==MotionEvent.ACTION_DOWN) {
initialXValue = event.getX();
return true;
}
if (event.action === MotionEvent.ACTION_MOVE) {
val diffX = event.x - initialXValue
if (diffX > 0 && direction === SwipeDirection.RIGHT) {
// swipe from left to right detected
return false
} else if (diffX < 0 && direction === SwipeDirection.LEFT) {
// swipe from right to left detected
return false
}
}
return true;
}
public void setAllowedSwipeDirection(SwipeDirection direction) {
this.direction = direction;
}
}
2.扩展 ViewPager(在 Kotlin 中)
enum class SwipeDirection {
ALL, LEFT, RIGHT, NONE
}
class SingleDirectionViewPager @JvmOverloads constructor(
context: Context,
attrs: AttributeSet?
) : ViewPager(context, attrs) {
private var initialXValue = 0f
private var direction: SwipeDirection = SwipeDirection.ALL
override fun onTouchEvent(event: MotionEvent): Boolean =
if (isSwipeAllowed(event)) {
super.onTouchEvent(event)
} else {
false
}
override fun onInterceptTouchEvent(event: MotionEvent): Boolean =
if (isSwipeAllowed(event)) {
super.onInterceptTouchEvent(event)
} else {
false
}
private fun isSwipeAllowed(event: MotionEvent): Boolean {
if (direction == SwipeDirection.ALL) {
return true
}
if (direction == SwipeDirection.NONE) {
return false
}
if (event.action == MotionEvent.ACTION_DOWN) {
initialXValue = event.x
return true
}
if (event.action == MotionEvent.ACTION_MOVE) {
val diffX = event.x - initialXValue
if (diffX > 0 && direction === SwipeDirection.RIGHT) {
// swipe from left to right detected
return false
} else if (diffX < 0 && direction === SwipeDirection.LEFT) {
// swipe from right to left detected
return false
}
}
return true
}
fun setAllowedSwipeDirection(direction: SwipeDirection) {
this.direction = direction
}
}
3.在布局中使用 viewPager
<package_name.customviewpager
android:id="@+id/customViewPager"
android:layout_height="match_parent"
android:layout_width="match_parent" />
4.在代码中启用任何滑动方向。默认为全部(左右)
mViewPager.setAllowedSwipeDirection(SwipeDirection.RIGHT);