Android—ScrollView源码分析及简单实现
一、ScrollView介绍及源码分析
ScrollView是Android日常开发中比较常见的一个ViewGroup,它只能有一个子View。用户在滑动时子View在ScrollView内部滚动,显示不同的区域。
在开发中如果需要将多个不同类型的视图垂直排列时,我们一般会使用ScrollView。但是永远不要将RecyclerView和ListView添加到ScrollView中,这会造成很不好的用户体验。并且ScrollView只支持纵向滑动,如果需要横向滑动,可以考虑使用HorizontalScrollView。
虽然ScrollView的功能比较简单,代码也不多,但是麻雀虽小,五脏俱全,其中包含了对事件拦截、滑动、多指等一系列的处理。通过分析其源码,可以对事件处理、View的滚动和Scroller的使用有个基础的认识。
1.1 预备知识。
1.1.1: 事件分发机制
这里不准备展开来讲这个复杂的话题,我们从宏观上来理解:由于事件是由父View向子View传递的,对于ViewGroup来说,可以通过onInterceptTouchEvent()
拦截某次事件来自己处理,也可以将其传递给子View。
对ScrollView来说,如果用户在上下滑动手指,那么就可以拦截此时的滑动事件并让子View上下滚动,哪怕你的手指在Button上,也不会触发它的点击事件,因为都被ScrollView消费掉了。
1.1.2: 多指处理
如果用户同时使用多根手指滑动ScrollView,那么ScrollView应该听谁的?Android给出的答案是:谁最后来的就听谁的。因此需要对每根手指进行编号来对多指触控进行管理,用于给手指编号的就是pointerId和pointerIndex。
在一次事件流(从第1根手指落下开始,到最后一根手指离开,之间的所有MotionEvent称为一次事件流)中,每根手指的pointerId都不会改变,但是pointerIndex会向前填充。
举个例子,这里从0开始计数:
第0根手指落下时,此时的所有的pointerId和pointerIndex为[(0: 0)];
.......
直到第3根手指落下时,值为[(0: 0), (1: 1), (2: 2), (3: 3)];
抬起第2根手指,值为[(0: 0), (1: 1), (3: 2)],可以发现,pointerId为2的值不见了,但是pointerId为3的手指的pointerIndex向前填补变成了2;
抬起pointerId为1的手指,值变为[(0: 0), (3: 1)],pointerId为3的手指的pointerIndex又往前填补了一位变为了1。
1.2 源码分析
1.2.1 测量
一般情况下ScrollView的子View高度是大于ScrollView本身高度的,但是按照传统的measure方式,子View的测量模式如果是AT_MOST
或者EXACTLY
,那么测量出的高度不会大于ScrollView,也就无法滑动。
因此ScrollView重写了measureChild()
和measureChildWithMargins ()
,将测量模式改成了UNSPECIFIED
,这样在测量时能够得到子View完整的高度。
@Override
protected void measureChild(View child, int parentWidthMeasureSpec,
int parentHeightMeasureSpec) {
ViewGroup.LayoutParams lp = child.getLayoutParams();
int childWidthMeasureSpec;
int childHeightMeasureSpec;
childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, mPaddingLeft
+ mPaddingRight, lp.width);
final int verticalPadding = mPaddingTop + mPaddingBottom;
childHeightMeasureSpec = MeasureSpec.makeSafeMeasureSpec(
Math.max(0, MeasureSpec.getSize(parentHeightMeasureSpec) - verticalPadding),
MeasureSpec.UNSPECIFIED);
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
@Override
protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed,
int parentHeightMeasureSpec, int heightUsed) {
final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
+ widthUsed, lp.width);
final int usedTotal = mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin +
heightUsed;
final int childHeightMeasureSpec = MeasureSpec.makeSafeMeasureSpec(
Math.max(0, MeasureSpec.getSize(parentHeightMeasureSpec) - usedTotal),
MeasureSpec.UNSPECIFIED);
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
1.2.2 事件拦截
ScrollView继承自FrameLayout,重写其onInterceptTouchEvent()
方法可以拦截事件:当该方法返回true时,事件交给ScrollView的onTouchEvent()
方法处理。那么什么时候需要将事件拦截呢?回忆一下我们使用ScrollView的场景,无非是两种情况:
一、手指上下移动的范围大于某个值,此时表示用户想滑动ScrollView。
二、ScrollView处于惯性滑动中,用户手指按下,则ScrollView停止滚动并且用户可以直接滑动。
在代码中,我们通过一个值mIsBeingDragged
来表示当前是否处于滑动状态,如果是,那么拦截事件。
精简后的代码如下,这里删除了和事件拦截无关的代码并添加了部分注释。
public boolean onInterceptTouchEvent(MotionEvent ev) {
/*
* 考虑最常见的一种情况:此时ScrollView处于滑动状态,
* 并且用户在滑动手指,则可以直接拦截该事件
*/
final int action = ev.getAction();
if ((action == MotionEvent.ACTION_MOVE) && (mIsBeingDragged)) {
return true;
}
//......
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_MOVE: {
/*
* 当手指移动的距离超过touchSlop时才开始拦截
*/
// 省略部分边界处理......
final int y = (int) ev.getY(pointerIndex);
final int yDiff = Math.abs(y - mLastMotionY);
if (yDiff > mTouchSlop) { // y上的滑动距离大于某个值
mIsBeingDragged = true;
mLastMotionY = y;
final ViewParent parent = getParent();
if (parent != null) {
parent.requestDisallowInterceptTouchEvent(true);
}
}
break;
}
case MotionEvent.ACTION_DOWN: {
final int y = (int) ev.getY();
/*
* 记录ACTION_DOWN时的坐标
* 此时的pointerIndex一定为0
*/
mLastMotionY = y;
mActivePointerId = ev.getPointerId(0);
/*
* 如果在惯性滑动时用户Down下,则设置为滑动状态。
* 我们需要先调用computeScrollOffset()之后isFinished()才会返回正确的值
*/
mScroller.computeScrollOffset();
mIsBeingDragged = !mScroller.isFinished();
break;
}
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
/* 手指抬起,取消滑动状态 */
mIsBeingDragged = false;
mActivePointerId = INVALID_POINTER;
// 省略回弹
break;
case MotionEvent.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
break;
}
/*
* 只有在滑动状态下ScrollView才需要拦截事件
*/
return mIsBeingDragged;
}
1.2.3 手指拖动及惯性滑动
当ScrollView将事件拦截后,就交给自身的onTouchEvent()
处理,总的来说onTouchEvent()
需要做两件事情:一是在用户ACTION_MOVE
时使ScrollView中的内容随着手指拖动;二是在用户ACTION_UP
时通过VelocityTracker计算速度并开启惯性滑动。
除了上面说的两个功能,ScrollView的onTouchEvent()
方法中还添加了嵌套滑动相关的功能,将这部分删掉,精简后的代码如下所示:
public boolean onTouchEvent(MotionEvent ev) {
initVelocityTrackerIfNotExists();
MotionEvent vtev = MotionEvent.obtain(ev);
final int actionMasked = ev.getActionMasked();
switch (actionMasked) {
case MotionEvent.ACTION_DOWN: {
if ((mIsBeingDragged = !mScroller.isFinished())) {
final ViewParent parent = getParent();
if (parent != null) {
parent.requestDisallowInterceptTouchEvent(true);
}
}
/*
* isFinished()为false时还处于fling,也就是惯性滑动中
* 如果用户此时触摸屏幕,则停止fling
*/
if (!mScroller.isFinished()) {
mScroller.abortAnimation();
}
mLastMotionY = (int) ev.getY();
mActivePointerId = ev.getPointerId(0);
break;
}
case MotionEvent.ACTION_MOVE:
final int activePointerIndex = ev.findPointerIndex(mActivePointerId);
// activePointerIndex非法值处理
if (activePointerIndex == -1) {
Log.e(TAG, "Invalid pointerId=" + mActivePointerId + " in onTouchEvent");
break;
}
final int y = (int) ev.getY(activePointerIndex);
int deltaY = mLastMotionY - y;
// 省略嵌套滑动dispatchNestedPreScroll部分......
if (!mIsBeingDragged && Math.abs(deltaY) > mTouchSlop) {
final ViewParent parent = getParent();
if (parent != null) {
parent.requestDisallowInterceptTouchEvent(true);
}
mIsBeingDragged = true;
// 优化滑动体验,可以去掉
if (deltaY > 0) {
deltaY -= mTouchSlop;
} else {
deltaY += mTouchSlop;
}
}
if (mIsBeingDragged) {
final int oldY = mScrollY;
final int range = getScrollRange();
final int overscrollMode = getOverScrollMode();
boolean canOverscroll = overscrollMode == OVER_SCROLL_ALWAYS ||
(overscrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0);
// overScrollBy(...)就是实际进行滚动的方法
if (overScrollBy(0, deltaY, 0, mScrollY, 0, range, 0, mOverscrollDistance, true)) {
// 当遇到滑动障碍时消除速度
mVelocityTracker.clear();
}
// 省略嵌套滑动dispatchNestedScroll部分......
if (canOverscroll) {
// 省略滑动到边缘时绘制的阴影......
}
}
break;
case MotionEvent.ACTION_UP:
if (mIsBeingDragged) {
final VelocityTracker velocityTracker = mVelocityTracker;
// 计算速度
velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
// 得到Y方向上的速度
int initialVelocity = (int) velocityTracker.getYVelocity(mActivePointerId);
if ((Math.abs(initialVelocity) > mMinimumVelocity)) {
// 开启惯性滑动,内部实际调用fling
flingWithNestedDispatch(-initialVelocity);
}
mActivePointerId = INVALID_POINTER;
endDrag();
}
break;
case MotionEvent.ACTION_CANCEL:
if (mIsBeingDragged && getChildCount() > 0) {
if (mScroller.springBack(mScrollX, mScrollY, 0, 0, 0, getScrollRange())) {
postInvalidateOnAnimation();
}
mActivePointerId = INVALID_POINTER;
endDrag();
}
break;
case MotionEvent.ACTION_POINTER_DOWN: {
final int index = ev.getActionIndex();
mLastMotionY = (int) ev.getY(index);
mActivePointerId = ev.getPointerId(index);
break;
}
case MotionEvent.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
mLastMotionY = (int) ev.getY(ev.findPointerIndex(mActivePointerId));
break;
}
// 将每次的事件添加到mVelocityTracker以便计算速度
if (mVelocityTracker != null) {
mVelocityTracker.addMovement(vtev);
}
vtev.recycle();
return true;
}
可以看到ACTION_MOVE
时调用了overScrollBy(...)
方法来进行滚动,该方法是View类中的方法,看一下它做了什么。
/**
* 为那些滑动时会超过边界的View提供滑动处理
* 调用这个方法的类需要重写onOverScrolled(int, int, boolean, boolean)方法
* View可以通过此方法处理任何touch或者fling的滑动
* @return true 说明滑动到了最大边界并被限制在了边界上
*/
protected boolean overScrollBy(int deltaX, int deltaY,
int scrollX, int scrollY,// 当前的x、y方向上的滑动值
int scrollRangeX, int scrollRangeY, // 最大的滑动距离
int maxOverScrollX, int maxOverScrollY,// 可以超过滑动距离多少
boolean isTouchEvent) {
final int overScrollMode = mOverScrollMode;
final boolean canScrollHorizontal =
computeHorizontalScrollRange() > computeHorizontalScrollExtent();
final boolean canScrollVertical =
computeVerticalScrollRange() > computeVerticalScrollExtent();
final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
(overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
(overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
int newScrollX = scrollX + deltaX;
if (!overScrollHorizontal) {
maxOverScrollX = 0;
}
int newScrollY = scrollY + deltaY;
if (!overScrollVertical) {
maxOverScrollY = 0;
}
// Clamp values if at the limits and record
final int left = -maxOverScrollX;
final int right = maxOverScrollX + scrollRangeX;
final int top = -maxOverScrollY;
final int bottom = maxOverScrollY + scrollRangeY;
boolean clampedX = false;
if (newScrollX > right) {
newScrollX = right;
clampedX = true;
} else if (newScrollX < left) {
newScrollX = left;
clampedX = true;
}
boolean clampedY = false;
if (newScrollY > bottom) {
newScrollY = bottom;
clampedY = true;
} else if (newScrollY < top) {
newScrollY = top;
clampedY = true;
}
// 调用重写的方法
onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
return clampedX || clampedY;
}
发现overScrollBy(...)
方法对滑动的最大距离进行了限制,但实际上并没有真的滑动View,该方法内部调用了onOverScrolled (...)
方法,由于ScrollView重写了该方法,那么调用的就是重写后的方法,代码如下所示。
如果当前不处于fling状态,用户通过手指拖动时触发ACTION_MOVE
事件,此时会运行到else代码块,最终通过scrollTo()
方法来滚动ScrollView中的内容。
protected void onOverScrolled(int scrollX, int scrollY,
boolean clampedX, boolean clampedY) {
if (!mScroller.isFinished()) { // 此时处于fling状态
final int oldX = mScrollX;
final int oldY = mScrollY;
mScrollX = scrollX;
mScrollY = scrollY;
invalidateParentIfNeeded();
onScrollChanged(mScrollX, mScrollY, oldX, oldY);
if (clampedY) {
mScroller.springBack(mScrollX, mScrollY, 0, 0, 0, getScrollRange());
}
} else {
super.scrollTo(scrollX, scrollY);
}
}
手指拖动时的逻辑讲完,来看一下惯性滑动。在onTouchEvent()
中,在ACTION_UP
时计算出了纵向的速度,然后调用flingWithNestedDispatch ()
方法开始惯性滑动,看名字就知道该方法也加入了嵌套滑动相关的功能,代码如下所示。
private void flingWithNestedDispatch(int velocityY) {
final boolean canFling = (mScrollY > 0 || velocityY > 0) &&
(mScrollY < getScrollRange() || velocityY < 0);
if (!dispatchNestedPreFling(0, velocityY)) {
dispatchNestedFling(0, velocityY, canFling);
if (canFling) {
fling(velocityY);
}
}
}
其实本质上就是调用了fling(int velocityY)
方法。
public void fling(int velocityY) {
if (getChildCount() > 0) {
int height = getHeight() - mPaddingBottom - mPaddingTop;
int bottom = getChildAt(0).getHeight();
mScroller.fling(mScrollX, mScrollY, 0, velocityY, 0, 0, 0,
Math.max(0, bottom - height), 0, height/2);
postInvalidateOnAnimation();
}
}
代码调用了OverScroller的fling(...)
方法和postInvalidateOnAnimation ()
方法。
OverScroller类只用于计算数值,其功能类似ValueAnimator,在调用fling(...)
方法之后,它内部就会计算某一时刻的ScrollY值应该为多少,我们在每次绘制的时候获取当前的ScrollY值并设置即可。那么具体该怎么做呢?
其中的关键就是View类中的computeScroll()
方法,这个方法会在View每次绘制的时候被调用,当你调用invalidate()
等重绘方法时,computeScroll()
也会被调用。
看下源码,发现是空实现,很明显是让我们重写它。注释说该方法一般被用于ViewGroup更新其子View的mScrollX和mScrollY值,并且基本是与Scroller配合使用的。
/**
* Called by a parent to request that a child update its values for mScrollX
* and mScrollY if necessary. This will typically be done if the child is
* animating a scroll using a {@link android.widget.Scroller Scroller}
* object.
*/
public void computeScroll() {
}
因此ScrollView的fling()
方法中的postInvalidateOnAnimation ()
方法最终还会触发ScrollView重写的computeScroll()
方法:
public void computeScroll() {
if (mScroller.computeScrollOffset()) { // mScroller的动画还没结束
int oldX = mScrollX;
int oldY = mScrollY;
int x = mScroller.getCurrX();
int y = mScroller.getCurrY();
if (oldX != x || oldY != y) {
final int range = getScrollRange();
overScrollBy(x - oldX, y - oldY, oldX, oldY, 0, range,
0, mOverflingDistance, false);
onScrollChanged(mScrollX, mScrollY, oldX, oldY);
}
if (!awakenScrollBars()) {
// 在动画结束前继续调用postInvalidateOnAnimation触发重绘
postInvalidateOnAnimation();
}
}
}
可以看到computeScroll()
内部调用了overScrollBy()
方法进行了移动,而在动画没有完全结束前,又会再次调用postInvalidateOnAnimation()
方法在下次绘制时继续移动。
二、简单实现
经过上面的分析可以发现ScrollView的基础功能并不难实现,下面是一个简单的版本,有基础的滑动和overScroll,不包含进度条、边缘的阴影和嵌套滑动,用法和ScrollView一致。
public class MyScrollView extends FrameLayout {
private int mTouchSlop;
private boolean mIsBeingDragged;
private int mActivePointerId = MotionEvent.INVALID_POINTER_ID;
private int mLastMotionY;
private OverScroller mScroller;
private VelocityTracker mVelocityTracker;
private int mMinimumVelocity;
private int mMaximumVelocity;
private int mOverscrollDistance;
private int mOverflingDistance;
public MyScrollView(@NonNull Context context) {
this(context, null);
}
public MyScrollView(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public MyScrollView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mScroller = new OverScroller(getContext());
setFocusable(true);
setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);
setWillNotDraw(false);
setOverScrollMode(OVER_SCROLL_ALWAYS);
final ViewConfiguration configuration = ViewConfiguration.get(getContext());
mTouchSlop = configuration.getScaledTouchSlop();
mMinimumVelocity = configuration.getScaledMinimumFlingVelocity();
mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
mOverscrollDistance = configuration.getScaledOverscrollDistance();
mOverflingDistance = configuration.getScaledOverflingDistance();
}
private void initOrResetVelocityTracker() {
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
} else {
mVelocityTracker.clear();
}
}
private void initVelocityTrackerIfNotExists() {
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
}
private void recycleVelocityTracker() {
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
final int action = ev.getAction();
if ((action == MotionEvent.ACTION_MOVE) && (mIsBeingDragged)) {
return true;
}
if (super.onInterceptTouchEvent(ev)) {
return true;
}
if (getScrollY() == 0 && !canScrollVertically(1)) {
return false;
}
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_MOVE: {
final int activePointerId = mActivePointerId;
if (activePointerId == MotionEvent.INVALID_POINTER_ID) {
break;
}
final int pointerIndex = ev.findPointerIndex(activePointerId);
if (pointerIndex == -1) {
Log.e("TAG", "Invalid pointerId=" + activePointerId
+ " in onInterceptTouchEvent");
break;
}
final int y = (int) ev.getY(pointerIndex);
final int yDiff = Math.abs(y - mLastMotionY);
if (yDiff > mTouchSlop) {
mIsBeingDragged = true;
mLastMotionY = y;
initVelocityTrackerIfNotExists();
mVelocityTracker.addMovement(ev);
final ViewParent parent = getParent();
if (parent != null) {
parent.requestDisallowInterceptTouchEvent(true);
}
}
break;
}
case MotionEvent.ACTION_DOWN: {
final int y = (int) ev.getY();
if (!inChild((int) ev.getX(), (int) y)) {
mIsBeingDragged = false;
recycleVelocityTracker();
break;
}
mLastMotionY = y;
mActivePointerId = ev.getPointerId(0);
initOrResetVelocityTracker();
mVelocityTracker.addMovement(ev);
mScroller.computeScrollOffset();
mIsBeingDragged = !mScroller.isFinished();
break;
}
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
mIsBeingDragged = false;
mActivePointerId = MotionEvent.INVALID_POINTER_ID;
recycleVelocityTracker();
if (mScroller.springBack(getScrollX(), getScrollY(), 0, 0,
0, getScrollRange())) {
postInvalidateOnAnimation();
}
break;
case MotionEvent.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
break;
}
return mIsBeingDragged;
}
private boolean inChild(int x, int y) {
if (getChildCount() > 0) {
final int scrollY = getScrollY();
final View child = getChildAt(0);
return !(y < child.getTop() - scrollY
|| y >= child.getBottom() - scrollY
|| x < child.getLeft()
|| x >= child.getRight());
}
return false;
}
@Override
protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) {
ViewGroup.LayoutParams lp = child.getLayoutParams();
int childWidthMeasureSpec;
int childHeightMeasureSpec;
childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, getPaddingLeft()
+ getPaddingRight(), lp.width);
final int verticalPadding = getPaddingTop() + getPaddingBottom();
childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
Math.max(0, MeasureSpec.getSize(parentHeightMeasureSpec) - verticalPadding),
MeasureSpec.UNSPECIFIED);
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
@Override
protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed) {
final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
getPaddingLeft() + getPaddingRight() + lp.leftMargin + lp.rightMargin
+ widthUsed, lp.width);
final int usedTotal = getPaddingTop() + getPaddingBottom() + lp.topMargin + lp.bottomMargin +
heightUsed;
final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
Math.max(0, MeasureSpec.getSize(parentHeightMeasureSpec) - usedTotal),
MeasureSpec.UNSPECIFIED);
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
private int getScrollRange() {
int scrollRange = 0;
if (getChildCount() > 0) {
View child = getChildAt(0);
scrollRange = Math.max(0,
child.getHeight() - (getHeight() - getPaddingBottom() - getPaddingTop()));
}
return scrollRange;
}
private void onSecondaryPointerUp(MotionEvent ev) {
final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
MotionEvent.ACTION_POINTER_INDEX_SHIFT;
final int pointerId = ev.getPointerId(pointerIndex);
if (pointerId == mActivePointerId) {
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mLastMotionY = (int) ev.getY(newPointerIndex);
mActivePointerId = ev.getPointerId(newPointerIndex);
if (mVelocityTracker != null) {
mVelocityTracker.clear();
}
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
initVelocityTrackerIfNotExists();
final int actionMasked = ev.getActionMasked();
switch (actionMasked) {
case MotionEvent.ACTION_DOWN: {
if (getChildCount() == 0) {
return false;
}
if ((mIsBeingDragged = !mScroller.isFinished())) {
final ViewParent parent = getParent();
if (parent != null) {
parent.requestDisallowInterceptTouchEvent(true);
}
}
if (!mScroller.isFinished()) {
mScroller.abortAnimation();
}
mLastMotionY = (int) ev.getY();
mActivePointerId = ev.getPointerId(0);
startNestedScroll(SCROLL_AXIS_VERTICAL);
break;
}
case MotionEvent.ACTION_MOVE:
final int activePointerIndex = ev.findPointerIndex(mActivePointerId);
if (activePointerIndex == -1) {
Log.e("TAG", "Invalid pointerId=" + mActivePointerId + " in onTouchEvent");
break;
}
final int y = (int) ev.getY(activePointerIndex);
int deltaY = mLastMotionY - y;
if (!mIsBeingDragged && Math.abs(deltaY) > mTouchSlop) {
final ViewParent parent = getParent();
if (parent != null) {
parent.requestDisallowInterceptTouchEvent(true);
}
mIsBeingDragged = true;
if (deltaY > 0) {
deltaY -= mTouchSlop;
} else {
deltaY += mTouchSlop;
}
}
if (mIsBeingDragged) {
mLastMotionY = y;
if (overScrollBy(0, deltaY, 0, getScrollY(), 0, getScrollRange(),
0, mOverscrollDistance, true)) {
// Break our velocity if we hit a scroll barrier.
mVelocityTracker.clear();
}
}
break;
case MotionEvent.ACTION_UP:
if (mIsBeingDragged) {
final VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
int initialVelocity = (int) velocityTracker.getYVelocity(mActivePointerId);
if ((Math.abs(initialVelocity) > mMinimumVelocity)) {
fling(-initialVelocity);
} else if (mScroller.springBack(getScrollX(), getScrollY(), 0, 0, 0,
getScrollRange())) {
postInvalidateOnAnimation();
}
mActivePointerId = MotionEvent.INVALID_POINTER_ID;
endDrag();
}
break;
case MotionEvent.ACTION_CANCEL:
if (mIsBeingDragged && getChildCount() > 0) {
if (mScroller.springBack(getScrollX(), getScrollY(), 0, 0,
0, getScrollRange())) {
postInvalidateOnAnimation();
}
mActivePointerId = MotionEvent.INVALID_POINTER_ID;
endDrag();
}
break;
case MotionEvent.ACTION_POINTER_DOWN: {
final int index = ev.getActionIndex();
mLastMotionY = (int) ev.getY(index);
mActivePointerId = ev.getPointerId(index);
break;
}
case MotionEvent.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
mLastMotionY = (int) ev.getY(ev.findPointerIndex(mActivePointerId));
break;
}
if (mVelocityTracker != null) {
mVelocityTracker.addMovement(ev);
}
return true;
}
public void fling(int velocityY) {
if (getChildCount() > 0) {
int height = getHeight() - getPaddingBottom() - getPaddingTop();
int bottom = getChildAt(0).getHeight();
mScroller.fling(getScrollX(), getScrollY(), 0, velocityY, 0, 0, 0,
Math.max(0, bottom - height), 0, height/2);
postInvalidateOnAnimation();
}
}
private void endDrag() {
mIsBeingDragged = false;
recycleVelocityTracker();
}
@Override
protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY) {
if (!mScroller.isFinished()) {
final int oldX = getScrollX();
final int oldY = getScrollY();
setScrollX(scrollX);
setScrollY(scrollY);
onScrollChanged(getScrollX(), getScrollY(), oldX, oldY);
if (clampedY) {
mScroller.springBack(getScrollX(), getScrollY(), 0, 0, 0, getScrollRange());
}
} else {
super.scrollTo(scrollX, scrollY);
}
}
@Override
public void computeScroll() {
if (mScroller.computeScrollOffset()) {
int oldX = getScrollX();
int oldY = getScrollY();
int x = mScroller.getCurrX();
int y = mScroller.getCurrY();
if (oldX != x || oldY != y) {
final int range = getScrollRange();
overScrollBy(x - oldX, y - oldY, oldX, oldY, 0, range,
0, mOverflingDistance, false);
onScrollChanged(getScrollX(), getScrollY(), oldX, oldY);
}
if (!awakenScrollBars()) {
// Keep on drawing until the animation has finished.
postInvalidateOnAnimation();
}
}
}
}
三、补充&总结
- ScrollView有一个属性叫fillViewPort,如果该属性设置为true,那么即使子View的高度小于ScrollView,它也会撑满ScrollView。具体可见ScrollView的
measure()
方法。 - ScrollView的嵌套滑动功能类似一个连接父Layout和子View的桥梁,本身没有实现具体的功能。
我的理解就是这样,如果有不同的意见和想法,欢迎在评论区讨论。