Skip to content

Instantly share code, notes, and snippets.

@patrickcousins
Last active September 21, 2016 12:20
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save patrickcousins/5699691 to your computer and use it in GitHub Desktop.
Save patrickcousins/5699691 to your computer and use it in GitHub Desktop.
VerticalSmoothScrollView from http://stackoverflow.com/questions/5193678/android-horizontalscrollview-smoothscroll-animation-time/13639106 Added vertical computation. NOTE: to use with API 8 or lower you need to find a compat Scroller, ViewPagerIndicator is a good source to look for a compat Scroller.
public class VerticalSmoothScrollView extends ScrollView
{
private OverScroller myScroller; //TODO implement our own scroller, Scroller and OverScroller can usually be swapped
public VerticalSmoothScrollView( Context context, AttributeSet attrs, int defStyle )
{
super( context, attrs, defStyle );
init();
}
public VerticalSmoothScrollView( Context context, AttributeSet attrs )
{
super( context, attrs);
init();
}
public VerticalSmoothScrollView( Context context)
{
super( context );
init();
}
private void init()
{
try
{
Class parent = this.getClass();
do
{
parent = parent.getSuperclass();
} while (!parent.getName().equals("android.widget.ScrollView"));
Log.i("Scroller", "class: " + parent.getName());
Field field = parent.getDeclaredField("mScroller");
field.setAccessible(true);
myScroller = (OverScroller) field.get(this);
} catch (NoSuchFieldException e)
{
e.printStackTrace();
} catch (IllegalArgumentException e)
{
e.printStackTrace();
} catch (IllegalAccessException e)
{
e.printStackTrace();
}
}
/**
* TODO! OverScroller is API 9 and NOT subclass of Scroller
*/
@SuppressLint("NewApi")
public void customSmoothScrollBy(int dx, int dy)
{
if (myScroller == null)
{
smoothScrollBy(dx, dy);
return;
}
if (getChildCount() == 0)
return;
final int width = getWidth() - getPaddingRight() - getPaddingLeft();
final int right = getChildAt(0).getWidth();
final int maxX = Math.max(0, right - width);
final int scrollX = getScrollX();
final int height = getHeight() - getPaddingTop() - getPaddingBottom();
final int bottom = getChildAt(0).getBottom();
final int maxY = Math.max(0, bottom - height);
final int scrollY = getScrollY();
dx = Math.max(0, Math.min(scrollX + dx, maxX)) - scrollX;
dy = Math.max(0, Math.min(scrollY + dy, maxY)) - scrollY;
myScroller.startScroll(scrollX, scrollY, dx, dy, 1500);
invalidate();
}
/**
* TODO! OverScroller is API 9 and NOT subclass of Scroller
*/
public void customSmoothScrollTo(int x, int y)
{
customSmoothScrollBy(x - getScrollX(), y - getScrollY());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment