Android ScrollView realizes horizontal and vertical drag rebound effect
- 2021-10-16 02:45:01
- OfStack
This article example for everyone to share the Android ScrollView drag rebound effect of the specific code, for your reference, the specific content is as follows
Principle
In the android 2.3 release, a new method was added to the View class: overScrollBy. By covering this method, the effect of damping rebound 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; // Last rebound 1 Secondary scroll, reset
}else{
newDeltaY = delta; // Increase damping effect
}
return super.overScrollBy(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; // Last rebound 1 Secondary scroll, reset
}else{
newDeltaX = delta; // Increase damping effect
}
return super.overScrollBy(newDeltaX, deltaY, scrollX, scrollY, scrollRangeX, scrollRangeY, MAX_SCROLL, maxOverScrollY, isTouchEvent);
}
}