自定义View解决滑动冲突

来源:互联网 发布:如何解决网络威胁 编辑:程序博客网 时间:2024/04/29 15:44

自定义View解决父View左右滑动,子View上下滑动引起的冲突。

参考《Android开发艺术探索》书中对于滑动冲突的的源码,修护了其中的一个bug。

如下:


从动图可以看到当你向左滑动时,突然向右轻轻的滑动一点,你却滑到了第二页,查看源码看到

case MotionEvent.ACTION_UP:{int scrollX = getScrollX();mVelocityTracker.computeCurrentVelocity(1000);float xVelocity = mVelocityTracker.getXVelocity();if (Math.abs(xVelocity) >= 100) {mChildIndex = xVelocity > 0 ? mChildIndex -1 : mChildIndex + 1;} else {mChildIndex = (scrollX + mChildIndex / 2) / mChildWidth;}mChildIndex = Math.max(0, Math.min(mChildIndex, mChildrenSize -1));int dx = mChildIndex * mChildWidth - scrollX;smoothScrollBy(dx,0);mVelocityTracker.clear();break;}

从上面代码看出,如果在离开屏幕时X方向速度的绝对值大于100和左右滑动超过一半的话,就改变当前页,xVelocity 速度为正当前页-1,xVelocity 速度为负当前页+1,如果沿X方向滑动的话,xVelocity的速度就为正,Android是以左上角为原点,往下为Y轴正方向,往右为X轴正方向。

从这里mChildIndex = xVelocity > 0 ? mChildIndex -1 : mChildIndex + 1;看出来,即使你之前是往左边滑动的,当你离开屏幕时往右边滑动了,它不会返回当前页,而是调到下一页。

更改之后

if (Math.abs(xVelocity) >= 100) {int index = scrollX / mChildWidth;mChildIndex = xVelocity > 0 ? (index == mChildIndex ? mChildIndex : mChildIndex - 1)  : (index < mChildIndex || scrollX < 0 ? mChildIndex : mChildIndex + 1);}

xVelocity >0时,如果它是一直往X轴正方向滑动(就是滑动轨迹是从左到右)的话index<mChildIndex,所以就是mChildIndex-1,如果之前是往X轴负方向滑动,只是最后离开屏幕才往正方向滑动的话index==mChildIndex的,所以就是mChildIndex

xVelocity <0时,如果它是一直往X轴负方向滑动的话index==mChildIndex,所以就是mChildIndex+1,如果之前是往X轴正方向滑动,只是最后离开屏幕才往正方向滑动的话index<mChildIndex的,所以就是mChildIndex

为什么这里还有一个scrollX < 0的判断呢,如果scrollX < mChildWidthscrollX < 0时,index=0,当前页如果是第一页(index=0),如果这时往X轴正方向滑动,但是在离开屏幕的时候却往X轴负方向滑动,这个时候的index=mChildIndex=0,所以它还是会给mChildIndex+1

下面是修改后的

源码github:https://github.com/AndroidFormWb/HorizontalScrollViewDemo

0 0
原创粉丝点击