使用scroller类实现自定义view的弹性滑动。
1.初始化scroller;
2.复写computeScroll()
方法,在内部实现滚动相关的业务逻辑,并进行postInvalidate()
的调用;
3.调用startScroll()
方法,并进行重绘invalidate()
;
实现ImageView
的动画:
核心代码:
public class ImageScrollerView extends LinearLayout {
private Scroller mScroller;
private int startX;
private int duration;
private boolean flag=true;
public ImageScrollerView(Context context) {
super(context);
}
public ImageScrollerView(Context context, AttributeSet attrs) {
super(context, attrs);
mScroller=new Scroller(context);
duration=3000;
}
@Override
public void computeScroll() {
if (mScroller.computeScrollOffset()){
scrollTo(mScroller.getCurrX(),0);
invalidate();
}
}
public void beginScroll(){
if(flag){
mScroller.startScroll(mScroller.getCurrX(),0,-250,0,duration);
startX=mScroller.getCurrX();
flag=false;
}else {
mScroller.startScroll(-startX,0,80,0,duration);
flag=true;
}
invalidate();
}
}
TextView实现内容移动,通过scrollBy和scrollTo方法