Android学习笔记 3.3View的弹性滑动

来源:互联网 发布:软件前景 编辑:程序博客网 时间:2024/05/18 09:06

1.使用Scroller

典型使用方法(在需要使用的地方调用soomthScrollTo()方法):

Scroller scroller;private void soomthScrollTo(int destX,int destY){int scrollX=getScrollX();int scrollY=getScrollY();int deltaX=destX-scrollX;int deltaY=destY-scrollY;scroller.startScroll(scrollX,scrollY,deltaX,deltaY,1000);invalidate();}public void computeScroll(){if(scroller.computeScrollOffset()){scrollTo(scroller.getCurrX(),scroller.getCurrY());postInvalidate();}}

Scroller本身不能实现view的滑动,他需要配合ViewcomputeScroll方法才能完成弹性滑动,它不断让View重绘,每次重绘距起始时间有个时间间隔,通过时间间隔就可以得出View当前的位置,然后通过scrollTo方法完成滑动。


2.使用动画

动画本身就是一种渐进的过程,因此具有弹性滑动的效果。

属性动画:

ObjectAnimator.ofFloat(target,"translationX",0,100).setDuration(100).start();


利用动画特性,模仿Scroller来实现View的弹性滑动:

final int startX=0,startY=0;final int deltaX=-100,deltaY=-100;final ValueAnimator animator =ValueAnimator.ofInt(0,1).setDuration(1000);animator.addUpdateListener(new AnimatorUpdateListener() {public void onAnimationUpdate(ValueAnimator animation) {// TODO Auto-generated method stubfloat fraction=animator.getAnimatedFraction();Anbtn.scrollTo(startX+(int)(deltaX*fraction), startY+(int)(deltaY*fraction));}});animator.start();


3.使用延时策略

它的核心思想是通过发送一系列延时消息从而达到一种渐进式的效果,具体可以使用HandlerViewpostDelayed方法,也可以使用线程的sleep方法。

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 Handler mHandler=new Handler(){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);Habtn.scrollTo(scrollX, 0);mHandler.sendEmptyMessageDelayed(MESSAGE_SCROLL_TO, DELAYED_TIME);}break;}};};



0 0
原创粉丝点击