SoFunction
Updated on 2025-03-01

Android ScrollView achieves horizontal and vertical drag rebound effects

The examples in this article share with you the specific code for Android ScrollView to achieve drag rebound effect for your reference. The specific content is as follows

principle

In android 2.3 version, a new method is added to the View class: overScrollBy. By covering this method, the damping rebound effect can be achieved.

Example 1.Vertical scroll

public class ReboundScrollView extends ScrollView{ 
 private static final int MAX_SCROLL = 200; 
 private static final float SCROLL_RATIO = 0.5f;// Damping coefficient  
 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;  //Rounce back for the last scroll, reset  }else{ 
   newDeltaY = delta;  //Increase the damping effect  } 
  return (deltaX, newDeltaY, scrollX, scrollY, scrollRangeX, scrollRangeY, maxOverScrollX, MAX_SCROLL, isTouchEvent);  
 } 
} 

Example 2.Scroll horizontally

public class ReboundHScrollView extends HorizontalScrollView{ 
 private static final int MAX_SCROLL = 200; 
 private static final float SCROLL_RATIO = 0.5f;// Damping coefficient  
 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;  //Rounce back for the last scroll, reset  }else{ 
   newDeltaX = delta;  //Increase the damping effect  } 
  return (newDeltaX, deltaY, scrollX, scrollY, scrollRangeX, scrollRangeY, MAX_SCROLL, maxOverScrollY, isTouchEvent);  
 } 
} 

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.