android view的scrollTo,scrollBy,computeScroll的理解

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.
注意这里的dx和dy,不要误以为是目标位置,它们表示的都是距离,这里的距离也是有方向的,和getScrollX的方向一致。


最后说说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,这样循环产生了滑动效果。


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值