原理

在android2.3版本中,View类中新增了一个方法:overScrollBy。通过覆盖该方法,就可以达到阻尼回弹的效果。

示例1、竖向滚动 

public class ReboundScrollView extends ScrollView{ 
  private static final int MAX_SCROLL = 200; 
  private static final float SCROLL_RATIO = 0.5f;// 阻尼系数  
   
  public ReboundScrollView(Context context) 
  { 
    super(context); 
  } 
 
  public ReboundScrollView(Context context, AttributeSet attrs) 
  { 
    super(context, attrs); 
  } 
 
  public ReboundScrollView(Context context, AttributeSet attrs, int defStyle) 
  { 
    super(context, attrs, defStyle); 
  } 
   
  @Override  
  protected boolean overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX, int scrollRangeY, int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent) 
  {   
    int newDeltaY = deltaY; 
    int delta = (int) (deltaY * SCROLL_RATIO); 
    if((scrollY+deltaY)==0 || (scrollY-scrollRangeY+deltaY)==0){  
      newDeltaY = deltaY;   //回弹最后一次滚动,复位 
    }else{ 
      newDeltaY = delta;   //增加阻尼效果 
    } 
    return super.overScrollBy(deltaX, newDeltaY, scrollX, scrollY, scrollRangeX, scrollRangeY, maxOverScrollX, MAX_SCROLL, isTouchEvent);   
  } 
} 

示例2、横向滚动

public class ReboundHScrollView extends HorizontalScrollView{ 
  private static final int MAX_SCROLL = 200; 
  private static final float SCROLL_RATIO = 0.5f;// 阻尼系数  
   
  public ReboundHScrollView(Context context) 
  { 
    super(context); 
  } 
 
  public ReboundHScrollView(Context context, AttributeSet attrs) 
  { 
    super(context, attrs); 
  } 
 
  public ReboundHScrollView(Context context, AttributeSet attrs, int defStyle) 
  { 
    super(context, attrs, defStyle); 
  } 
   
  @Override  
  protected boolean overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX, int scrollRangeY, int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent) 
  {   
    int newDeltaX = deltaX; 
    int delta = (int) (deltaX * SCROLL_RATIO); 
    if((scrollX+deltaX)==0 || (scrollX-scrollRangeX+deltaX)==0){  
      newDeltaX = deltaX;   //回弹最后一次滚动,复位 
    }else{ 
      newDeltaX = delta;   //增加阻尼效果 
    } 
    return super.overScrollBy(newDeltaX, deltaY, scrollX, scrollY, scrollRangeX, scrollRangeY, MAX_SCROLL, maxOverScrollY, isTouchEvent);   
  } 
} 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

收藏 打印