一、简介
Android手机因为屏幕比较小,为了给用户展示更多的内容需要使用滑动来隐藏和显示一些内容。因此滑动是Android中非常重要的知识点。View的滑动
二、View滑动的实现方式
1、scrollTo和scrollBy
scrollBy的源码如下:
public void scrollBy(int x, int y) {
scrollTo(mScrollX + x, mScrollY + y);
}
mScrollX表示当前移动的距离,scrollBy其实也是调用scrollTo。scrollTo就是移动到坐标(x,y),scrollBy是水平移动x,竖直移动y。scrollBy和scrollTo移动的是View中的内容,View在布局中的位置没有变。向左移动x为负,向上移动y为负,这点和android的坐标体系是相反的。调用后x、y、left、top、translationX以及translationY都不会改变,只有scrollX、scrollY改变。调用方式:
View.scrollTo()或者View.scrollBy()
2、translationX和translationY
Android3.0开始,View增加了几个参数:x、y、translationX以及translationY。x、y是View左上角的位置,translationX、translationY是View左上角相对于父容器的偏移量。其中x=left+translationX,y=left+translationY。因此设置translationX和translationY后View的left、top不会改变,x、y会改变。可以通过如下方式设置:
1)、View.settranslationX()和View.settranslationY()设置
2)、通过属性动画设置:ObjectAnimator.ofFloat(View, "translationX", 0, 200).setDuration(1000).start();
将一个View在1秒内向右移动200个像素
3、offsetLeftAndRight和offsetTopAndBottom
通过View.offsetLeftAndRight(move)调用,参数表示移动的像素。该方法会改变left、top,因此也会改变x、y。
4、通过View.layout()方法
用这个方法还不如用offsetLeftAndRight,用offsetLeftAndRight更加简单。
5、通过layoutParams利用设置边距完成view的移动
但是个人建议不使用这种
三、弹性滑动
上面的滑动都是一瞬间完成,不管滑动距离的大小都是一瞬间完成,这种体验非常不好。所以要进行弹性滑动,也是渐进性滑动。
1、使用Scroller使用
使用Scroller有点复杂,需要实现一些方法。具体使用方法如下:
1)、首先定义Scroller对象
scroller = new Scroller(getContext());
2)、在View中定义弹性滑动调用方法
public void startSmoothScroll(int destX, int destY, int duration){
int scrollX = getScrollX();
int scrollY = getScrollY();
int moveX = destX - scrollX;
int moveY = destY - scrollY;
scroller.startScroll(scrollX, scrollY, -moveX, -moveY, duration);
invalidate();
}
主要要调用invalidate()引起重绘调用onDraw(),在onDraw中调用computeScroll
3)、重写computeScroll
@Override
public void computeScroll() {
if(scroller.computeScrollOffset()) {
scrollTo(scroller.getCurrX(), scroller.getCurrY());
postInvalidate();
}
}
调用scroller.computeScrollOffset()计算下一次应该滑动的目的位置,返回true表示还没有滑动到目标位置,然后调用scrollTo滑动到scroller.computeScrollOffset()计算的下一次滑动的目的位置,目的位置通过scroller.getCurrX()和scroller.getCurrY()获得。主要要再次调用postInvalidate引起下一次onDraw调用computeScroll。
其实Scroller弹性滑动的大致原理就是Scroller计算下一次滑动的位置,然后调用scrollTo滑动到该位置。Scroller把到最终位置分成了很多段,因此是渐进式的效果。
2、通过动画实现弹性滑动
ObjectAnimator.ofFloat(View, "translationX", 0, 200).setDuration(1000).start();
将一个View在1秒内向右移动200个像素。