记录下系统提供的 View 滑动的 API 方法。不管采用哪一种方式,本质的思想基本上都是一致的,当触摸 View 的时候,记录下当前触摸点的坐标,当手指移动的时候,记录移动后的触摸点坐标,从而获取相对上一次坐标点的偏移量,通过偏移量来修改 View 的坐标,这样不断重复,从而实现滑动过程。
- layout 方法
@Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
lastX = x;
lastY = y;
break;
case MotionEvent.ACTION_MOVE:
int offsetX = x - lastX;// x 方向偏移量
int offsetY = y - lastY;// y 方向偏移量
layout(getLeft() + offsetX,
getTop() + offsetY,
getRight() + offsetX,
getBottom() + offsetY);
break;
}
return true;
}
offsetLeftAndRight() 和 offsetTopAndBottom()
这个方法相当于系统对左右,上下移动的 API 的封装。LayoutParams
LayoutParams 保存了一个 View 的布局参数,比如 width 和 height 参数,我们在通过 getLayoutParams() 获取 View 的 LayoutParams 时候要主要父容器的类型,比如父布局是 LinearLayout ,那么就用 LinearLayout.LayoutParams ,当然我们可以用他们的父类 ViewGroup.MarginLayoutParams 来处理,代码如下:
ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) getLayoutParams();
layoutParams.leftMargin = getLeft() + offsetX;
layoutParams.topMargin = getTop() + offsetY;
setLayoutParams(layoutParams);
- scrollTo 和 scrollBy
((View) getParent()).scrollBy(-offsetX, -offsetY);
Scroller
Scroller 是我们在实现弹性滑动中非常重要的角色,Scroller 在使用中需要注意下面几点。- 初始化Scroller
重写 computeScroll() 方法
@Override public void computeScroll() { super.computeScroll(); //判断 Scroller 是否执行完毕 if (mScroller.computeScrollOffset()) { ((View) getParent()).scrollTo(mScroller.getCurrX(), mScroller.getCurrY()); //通过重绘来不断调用 invalidate(); } }
startScroll 开始弹性滑动
public void startScroll(int startX, int startY, int dx, int dy)
参数分别是 x 方向和 y 方向起始点,和 偏移的距离。
属性动画
- ViewDragHelper
ViewDragHelper 的具体用法和讲解请看另一篇文章