28
votes

I wish to move smoothly to next scroll position in my custom view (on button press or event). How to implement this? First of all I can't see scroll animation class (only alpha, rotate, scale and translate). Secondly, having animation class, I can't see iterative one (say to scroll 100 pixels rights whatever position we have) only absolute ones (i.e. to animate from one constant value to another).

4

4 Answers

45
votes
39
votes

Using ObjectAnimator, this is a sample for scrolling to top:

public void scrollToTop() {
    int x = 0;
    int y = 0;

    ObjectAnimator xTranslate = ObjectAnimator.ofInt(mScrollView, "scrollX", x);
    ObjectAnimator yTranslate = ObjectAnimator.ofInt(mScrollView, "scrollY", y);

    AnimatorSet animators = new AnimatorSet();
    animators.setDuration(1000L);
    animators.playTogether(xTranslate, yTranslate);

    animators.addListener(new AnimatorListener() {

        @Override
        public void onAnimationStart(Animator arg0) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onAnimationRepeat(Animator arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onAnimationEnd(Animator arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onAnimationCancel(Animator arg0) {
            // TODO Auto-generated method stub

        }
    });
    animators.start();
}
1
votes

Animating scroll is done through a combination of using Scroller/OverScroller (to compute the time interpolated values of your scroll offsets), GestureDetectors (to start the scroller object) and the onComputeScroll method of a View (which implicitly is your animation loop).

The official android docs now have a detailed tutorial on precisely this topic. http://developer.android.com/training/gestures/scroll.html

0
votes

See the view_cache_demo sample code to see how to do animated scrolling. It works in 2D, caches complex drawing and also handles fling gestures, but you can simplify all that as necessary.