android scrollTo与scrollby 的区别以及

View的scrollBy()和scrollTo()

在分析scrollBy()和scrollTo()之前,先上一段源码片段:
/**
     * 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);
    }

scrollBy()和scrollTo()的滚动不同点

  • scrollTo(x, y):通过invalidate使view直接滚动到参数x和y所标定的坐标
  • scrollBy(x, y):通过相对于当前坐标的滚动。从上面代码中,很容以就能看出scrollBy()的方法体只有调用scrollTo()方法的一行代码,scrollBy()方法先对属性mScollX加上参数x和属性mScrollY加上参数y,然后将上述结果作为参数传入调用方法scrollTo()

我们先弄两个button,然后一个点击三次看效果

BT1.scrollTo(50,0);点击三次

BT2.scrollBy(-50,0);点击三次

下面是点击三次的效果


那为什么传入正数就往负坐标移动呢?传负数就往正坐标移动呢?来,我们看看源码

最后这个view肯定要调用 draw 方法,从新绘制的
public void draw(Canvas canvas) {
 // Step 6, draw decorations (foreground, scrollbars)
            onDrawForeground(canvas);


public void onDrawForeground(Canvas canvas) {
        onDrawScrollIndicators(canvas);
        onDrawScrollBars(canvas);
		


		
protected final void onDrawScrollBars(Canvas canvas) {
       if (invalidate) {
                        invalidate(bounds);
                    }
					}
		
public void invalidate(Rect dirty) {
        final int scrollX = mScrollX;
        final int scrollY = mScrollY;
        invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
                dirty.right - scrollX, dirty.bottom - scrollY, true, false);
    }
看到这个invalidate 方法我们就清楚了,dirty.left-scrollx  如果是负数相减,肯定是正数  dirty.right-scrollx  肯定是负数   所以方向相反了。

不知道我这样分析对不对,先记录一下吧!欢迎大牛指导

getRawX、getRawY与getX、getY的区别  以及getSorollY 和getScorollX 获取的大小
这个我就不废话了,getRawX是相对屏幕坐上角XY计算的,也就是从0,0点开始算起。

getX和getY是相对于本身控件

图片借别人的,说明一下




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值