Scroller一般主要用在自定义View 布局中;
public class MyView extends ViewGroup {
private int mLastMotionX;
private int mLastMotionY;
private Scroller mScroller;
private VelocityTracker mVelocity;
public MyView(Context context,AttributeSet attri){
this(context,attri,0);
}
public MyView(Context context,AttributeSet attri ,int defstyle){
super(context,attri,defstyle);
mScroller = new Scroller(context);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
// TODO Auto-generated method stub
int childCount= this.getChildCount();
View childView;
int leftBound = 0;
for(int i=0; i< childCount; i++){
childView = this.getChildAt(i);
if(childView.getVisibility() != View.GONE){
final int width = childView.getMeasuredWidth();
childView.layout(leftBound, 0, leftBound + width, childView.getMeasuredHeight());
leftBound += width;
}
}
}
@Override
protected void onMeasure(int widthMeasureSpec,int heightMeasureSpec){
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int childCount= this.getChildCount();
View childView;
for(int i=0; i< childCount; i++){
childView = this.getChildAt(i);
childView.measure(widthMeasureSpec, heightMeasureSpec);
}
}
@Override
public boolean onTouchEvent(MotionEvent ev){
if(null != mVelocity){
mVelocity = VelocityTracker.obtain();
mVelocity.addMovement(ev);
mVelocity.computeCurrentVelocity(1000);
}
float downX = ev.getX();
float downY = ev.getY();
switch(ev.getAction()){
case MotionEvent.ACTION_DOWN:
if(!mScroller.isFinished()){
mScroller.abortAnimation();
}
mLastMotionX = (int) downX;
mLastMotionY = (int) downY;
break;
case MotionEvent.ACTION_MOVE:
int deltaX = (int) (ev.getX() - mLastMotionX);
mLastMotionX = (int) ev.getX();
Log.i("luke", "deltaX="+deltaX);
/* if(deltaX > 0){
smoothScrollBy(-deltaX,0);
}else {
smoothScrollBy(deltaX,0);
} */
scrollBy(deltaX,0);
//smoothScrollTo(deltaX,0);
// smoothScrollBy(deltaX,0);
break;
case MotionEvent.ACTION_UP:
if(null != mVelocity){
mVelocity.recycle();
mVelocity = null;
}
int delta = - getScrollX();
mScroller.startScroll(getScrollX(), 0, delta, 0, 500);
invalidate();
break;
}
return true;
}
//调用此方法设置滚动的相对偏移
public void smoothScrollBy(int dx, int dy) {
//设置mScroller的滚动偏移量
mScroller.startScroll(mScroller.getStartX(), 0 , dx, dy,Math.abs(dx)*3);
postInvalidate();;//这里必须调用invalidate()才能保证computeScroll()会被调用,否则不一定会刷新界面,看不到滚动效果
}
private void smoothScrollTo2(int detalX,int deltaY){
mScroller.startScroll(mScroller.getCurrX(),0, detalX, 0, Math.abs(detalX)*3);
postInvalidate();
}
//调用此方法滚动到目标位置
public void smoothScrollTo(int fx, int fy) {
int dx = fx - mScroller.getFinalX();
int dy = fy - mScroller.getFinalY();
smoothScrollBy(dx, dy);
}
@Override
public void computeScroll() {
if (mScroller.computeScrollOffset()) {
scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
postInvalidate();
}
}