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是相对于本身控件
图片借别人的,说明一下