View和Scroller可以配合起来实现动态可控的滑动效果。
在View中有scrollTo和scrollBy方法,这两个方法其实是一样的,只是scrollTo是直接滑动到制定的位置,而scrollBy是滑动相对的距离。
先说说scroll的方向问题。view有个方法是getScrollX(),即获得当前滚动的位置,官方文档的解释是:
Return the scrolled left position of this view. This is the left edge of the displayed part of your view. You do not need to draw any pixels farther left, since those are outside of the frame of your view on screen.
就拿安卓桌面来举个例子,如果你手指往右滑,那么view.getScrollX()获得的值为一个负数,绝对值大小为滑动的距离。
现在说Scroller控制view滑动的方法startScroll(int startX,int startY,int dx,int dy);看看官方文档
Start scrolling by providing a starting point and the distance to travel. The scroll will use the default value of 250 milliseconds for the duration.
Parameters
startX | Starting horizontal scroll offset in pixels. Positive numbers will scroll the content to the left. |
---|---|
startY | Starting vertical scroll offset in pixels. Positive numbers will scroll the content up. |
dx | Horizontal distance to travel. Positive numbers will scroll the content to the left. |
dy | Vertical distance to travel. Positive numbers will scroll the content up. |
最后说说computeScroll,当调用startScroll方法后,scroller并不是直接包办一切,它只是帮助你计算每次移动的偏移量,你需要重写computeScroll方法,并在里面处理移动。如下是一个简单的例子
@Override
public void computeScroll(){
if(mScroller.computeScrollOffset()){
this.scrollTo(mScroller.getCurrX(),mScroller.getCurrY());
this.postInvalidate();
}
}
注意,在调用startScroll之后一定要调用invalidate,invalidate调用computeScroll,然后computeScroll又调用invalidate,这样循环产生了滑动效果。