How to animate scroll position? How to scroll smoo

2019-02-05 21:30发布

问题:

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

回答1:

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

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



回答2:

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

public void scroolToTop() {
            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();
}


回答3:

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



回答4:

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.