android ScrollView smoothScrollTo源码的一点理解

来源:互联网 发布:md5加密Java应用 密钥 编辑:程序博客网 时间:2024/06/11 19:50

项目中用到smoothScrollTo,作为一个老程序员有点汗颜,还真是不知道原理是啥,于是在网络上搜索一番,没有看到理想的结果。于是乎静下心来去看源码吧。

/**     * Like {@link #scrollTo}, but scroll smoothly instead of immediately.     *     * @param x the position where to scroll on the X axis     * @param y the position where to scroll on the Y axis     */    public final void smoothScrollTo(int x, int y) {        smoothScrollBy(x - mScrollX, y - mScrollY);    }
首先先搞清楚这里边的几个参数的含义:先说x,和y,这两个传入的参数就是你想要移动到的位置,这个位置就你要移动到的位置,当然是相对于ScrollView左上角的位置来说。mScrollX和mScrollY就是当前ScrollView的偏移量,也是相对于ScrollView的坐上角来说的,这两项的差值就是要滚动到的位置相对于当前ScrollView显示的左上角的坐标的一个相对位置。下面在放上smoothScrollBy的源码

/**     * Like {@link View#scrollBy}, but scroll smoothly instead of immediately.     *     * @param dx the number of pixels to scroll by on the X axis     * @param dy the number of pixels to scroll by on the Y axis     */    public final void smoothScrollBy(int dx, int dy) {        if (getChildCount() == 0) {            // Nothing to do.            return;        }        long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll;        if (duration > ANIMATED_SCROLL_GAP) {            final int height = getHeight() - mPaddingBottom - mPaddingTop;            final int bottom = getChildAt(0).getHeight();            final int maxY = Math.max(0, bottom - height);            final int scrollY = mScrollY;            dy = Math.max(0, Math.min(scrollY + dy, maxY)) - scrollY;            mScroller.startScroll(mScrollX, scrollY, 0, dy);            postInvalidateOnAnimation();        } else {            if (!mScroller.isFinished()) {                mScroller.abortAnimation();                if (mFlingStrictSpan != null) {                    mFlingStrictSpan.finish();                    mFlingStrictSpan = null;                }            }            scrollBy(dx, dy);        }        mLastScroll = AnimationUtils.currentAnimationTimeMillis();    }

首先说第8行,很简单,如果ScrollView没有包含任何东西,则什么都处理。(当然了,没有东西滚动毛线!)。然后说一下AnimationUtils.currentAnimationTimeMillis(),这个是获取从开机到现在的毫秒数。maxY计算的是超出ScrollView能够显示的那一部分的长度。dy计算出来的就是要滑动的距离。当然有人会问为什么还有判断if (duration > ANIMATED_SCROLL_GAP),这里是判断当前scrollView是否在滚动中,系统默认的滚动时间是250毫秒。我看网上很多人在问为什么设置的smoothScrollTo没有效果,就是因为计算出来的那个dy是0,这样就不会滚动了。所以解决这个问题还是要看自己设置的那个值为啥不对吧。

0 0