1、View使用Scroller滑动
/**
* 在scroller.startScroll()方法中,会将scrollX和deltaX相加存入mFinalX中
* invalidate()方法会调用draw()方法,draw()会调用computeScroll()方法,而在View
* 中computeScroll()方法是空实现,所以要复写该方法,在方法中调用
* scrollTo(scroller.getCurrX(), scroller.getCurrY()),又因为getCurrX()方法返回的是mFinalX
* 的值,调用postInvalidate()方法进行第二次重绘实现view的刷新
*/
Scroller scroller = new Scroller(mContext);
private void smoothScrollTo(int destX, int destY) {
int scrollX = getScrollX();
int deltaX = destX - scrollX;
// 1000ms内滑向destX,效果就是慢慢滑动
scroller.startScroll(scrollX, 0, deltaX, 0, 1000);
invalidate();
}
@Override
public void computeScroll() {
if (scroller.computeScrollOffset()) {
scrollTo(scroller.getCurrX(), scroller.getCurrY());
postInvalidate();
}
}
2、使用动画
final int startX = 0;
final int deltaX = 100;
final Button mButton = new Button(mContext);
ValueAnimator animator = ValueAnimator.ofInt(0, 1).setDuration(1000);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animator) {
float fraction = animator.getAnimatedFraction();
mButton.scrollTo(startX + (int) (deltaX * fraction), 0);
}
});
animator.start();
3、使用延时加载 Handler
private static final int MESSAGE_SCROLL_TO = 1;
private static final int FRAME_COUNT = 30;
private static final int DELAYED_TIME = 33;
private int mCount = 0;
private Button mButton;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_SCROLL_TO:
mCount++;
if (mCount <= FRAME_COUNT) {
float fraction = mCount / (float) FRAME_COUNT;
int scrollX = (int) (fraction * 100);
mButton.scrollTo(scrollX, 0);
mHandler.sendEmptyMessageDelayed(MESSAGE_SCROLL_TO, DELAYED_TIME);
}
break;
}
}
};