一、效果图
二、具体修改的代码
判断是否需要回弹的代码修改前后对比(点击查看 修改出处)
/**
* 判断是否需要弹性
*
* @return
*/
// public boolean isNeedMove() {
// int offset = childView.getMeasuredHeight() - getHeight();// 到底
// int scroll = getScrollY();// 到顶
// return scroll == 0 || offset == scroll;
// }
/**
* 判断是顶部回弹还是底部回弹
*
* @return 0-顶部 1-底部 2-中间
*/
public int moveLocation() {
int offset = childView.getMeasuredHeight() - getHeight();
int scroll = getScrollY();
if (scroll == 0) return 0;// 到顶
if (offset == scroll) return 1;// 到底
return 2;
}
滑动逻辑部分的修改前后对比
case MotionEvent.ACTION_MOVE:
if (moveLocation() == 0) {// 顶部回弹(底部回弹类似写法)
int distance = 0;
float nowY = ev.getY();
if (nowY - downY > 0) {// 判断是否是手指向下滑动
isCount = true;// 开启回弹
} else {
isCount = false;// 关闭回弹
}
if (nowY - y > 0 && isCount) {// 手指向下滑动
distance = 10;// 每次调用偏移的距离
}
if (nowY - y < 0 && isCount) {// 手指向上滑动
distance = -10;
}
y = nowY;
if (childView.getTop() < 500) {// 不能超过500
childView.layout(childView.getLeft(), childView.getTop() + distance, childView.getRight(), childView.getBottom() + distance);
}
if (isCount) {// 消耗事件
return true;
} else {// 交由父类
return super.onTouchEvent(ev);
}
}
// if (isNeedMove() || isCount) {
// float nowY = ev.getY();
// // 现在的位置和上次位置的差
// int distanceY = (int) (nowY - y);
//
// if (!isCount) {// 保证每次从0开始,因为这里的startY是全局变量 有点时候第一次 nowY - startY<0 有的时候>>0
// distanceY = 0; // 在这里要归0.
// }
// y = nowY;
// // 从新摆放子View的位置
// Log.d("aaa", "distanceY = " + distanceY + "---childView.getTop()=" + childView.getTop());
//
// childView.layout(childView.getLeft(), childView.getTop() + distanceY / 3,
// childView.getRight(), childView.getBottom() + distanceY / 3);
// isCount = true;
// }
break;