您的位置:首页 > 其它

Scroller分析

2015-10-23 10:26 260 查看
  先上源代码:

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Scroller;

public class CustomView extends LinearLayout {

private static final String TAG = "Scroller";

private Scroller mScroller;

public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
mScroller = new Scroller(context);
}

//调用此方法滚动到目标位置
public void smoothScrollTo(int fx, int fy) {
int dx = fx - mScroller.getFinalX();
int dy = fy - mScroller.getFinalY();
smoothScrollBy(dx, dy);
}

//调用此方法设置滚动的相对偏移
public void smoothScrollBy(int dx, int dy) {

//设置mScroller的滚动偏移量
mScroller.startScroll(mScroller.getFinalX(), mScroller.getFinalY(), dx, dy);
invalidate();//这里必须调用invalidate()才能保证computeScroll()会被调用,否则不一定会刷新界面,看不到滚动效果
}

@Override
public void computeScroll() {

//先判断mScroller滚动是否完成
if (mScroller.computeScrollOffset()) {

//这里调用View的scrollTo()完成实际的滚动
scrollTo(mScroller.getCurrX(), mScroller.getCurrY());

//必须调用该方法,否则不一定能看到滚动效果
postInvalidate();
}
super.computeScroll();
}
}


我们先来看一下,Scroller,这个对象里有startScroll方法

void android.widget.Scroller.startScroll(int startX, int startY, int dx, int dy, int duration)

第一个参数是起始移动的x坐标值,第二个是起始移动的y坐标值,第三个第四个参数都是移到某点的坐标值,而duration 当然就是执行移动的时间。这个有什么用呢。要知道有什么用还得再看一个方法

boolean android.widget.Scroller.computeScrollOffset()

当startScroll执行过程中即在duration时间内,computeScrollOffset 方法会一直返回false,但当动画执行完成后会返回返加true.

有了这两个方法还不够,我们还需要再重写viewGroup的一个方法,

computeScroll 这个方法什么时候会被调用呢

官网上这样说的

public void computeScroll ()

Since: API Level 1

Called by a parent to request that a child update its values for mScrollX and mScrollY if necessary. This will typically be done if the child is animating a scroll using a
Scroller
object.

当我们执行ontouch或invalidate()或postInvalidate()都会导致这个方法的执行

所以我们像下面这样调用,[b]postInvalidate执行后,会去调[b]computeScroll 方法,而这个方法里再去调[b]postInvalidate,这样[/b][/b]就可以不断地去调用scrollTo方法了,直到mScroller动画结束,当然第一次时,我们需要手动去调用一次postInvalidate才会去调用 [/b]

转自:http://www.cnblogs.com/lqminn/archive/2013/01/18/2867035.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: