29

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).

Suzan Cioc
  • 29,281
  • 63
  • 213
  • 385

4 Answers4

46

Assuming you are using a ScrollView, does smoothScrollTo(...) work for you?

http://developer.android.com/reference/android/widget/ScrollView.html#smoothScrollTo%28int,%20int%29

Ian Warwick
  • 4,774
  • 3
  • 27
  • 27
39

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();
}
Keale
  • 3,924
  • 3
  • 29
  • 46
anton46
  • 391
  • 3
  • 3
1

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

numan salati
  • 19,394
  • 9
  • 63
  • 66
0

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.

Lawrence D'Oliveiro
  • 2,768
  • 1
  • 15
  • 13