当前位置: 首页 > 工具软件 > ScrollTo > 使用案例 >

Android View scrollTo()和scroll()By()学习备忘

薄伟彦
2023-12-01

源码

我们先看下源码,然后再做下总结


    /**
     * The offset, in pixels, by which the content of this view is scrolled
     * horizontally.
     * {@hide}
     */
    @ViewDebug.ExportedProperty(category = "scrolling")
    protected int mScrollX;

    /**
     * The offset, in pixels, by which the content of this view is scrolled
     * vertically.
     * {@hide}
     */
    @ViewDebug.ExportedProperty(category = "scrolling")
    protected int mScrollY;


    /**
     * Set the scrolled position of your view. This will cause a call to
     * {@link #onScrollChanged(int, int, int, int)} and the view will be
     * invalidated.
     * @param x the x position to scroll to
     * @param y the y position to scroll to
     */
    public void scrollTo(int x, int y) {
        if (mScrollX != x || mScrollY != y) {
            int oldX = mScrollX;
            int oldY = mScrollY;
            mScrollX = x;
            mScrollY = y;
            invalidateParentCaches();
            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
            if (!awakenScrollBars()) {
                postInvalidateOnAnimation();
            }
        }
    }

    /**
     * Move the scrolled position of your view. This will cause a call to
     * {@link #onScrollChanged(int, int, int, int)} and the view will be
     * invalidated.
     * @param x the amount of pixels to scroll by horizontally
     * @param y the amount of pixels to scroll by vertically
     */
    public void scrollBy(int x, int y) {
        scrollTo(mScrollX + x, mScrollY + y);
    }

总结

  • scroll滑动的是View的内容而不是View的实际位置,比如滑动一个TextView,滑动的是里面的文字内容,背景并不会移动
  • scroll改变的是mScrollX和mScrollY的值
  • mScrollX值为正,内容向左移,值为负,内容向右移
  • mScrollY值为正,内容向上移,值为负,内容向下移
  • scrollBy()内部实际调用的是scrollTo()方法,scrollBy实现的是相对移动,scrollTo()实现的是绝对移动

 类似资料: