NestedScrollView.java revision 236bf5bc5041e4bf356eac3855fd4fcf72cd6994
1/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17
18package android.support.v4.widget;
19
20import android.content.Context;
21import android.content.res.TypedArray;
22import android.graphics.Canvas;
23import android.graphics.Rect;
24import android.os.Bundle;
25import android.os.Parcel;
26import android.os.Parcelable;
27import android.support.v4.view.AccessibilityDelegateCompat;
28import android.support.v4.view.InputDeviceCompat;
29import android.support.v4.view.MotionEventCompat;
30import android.support.v4.view.NestedScrollingChild;
31import android.support.v4.view.NestedScrollingChildHelper;
32import android.support.v4.view.NestedScrollingParent;
33import android.support.v4.view.NestedScrollingParentHelper;
34import android.support.v4.view.ScrollingView;
35import android.support.v4.view.VelocityTrackerCompat;
36import android.support.v4.view.ViewCompat;
37import android.support.v4.view.accessibility.AccessibilityEventCompat;
38import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
39import android.support.v4.view.accessibility.AccessibilityRecordCompat;
40import android.util.AttributeSet;
41import android.util.Log;
42import android.util.TypedValue;
43import android.view.FocusFinder;
44import android.view.KeyEvent;
45import android.view.MotionEvent;
46import android.view.VelocityTracker;
47import android.view.View;
48import android.view.ViewConfiguration;
49import android.view.ViewGroup;
50import android.view.ViewParent;
51import android.view.accessibility.AccessibilityEvent;
52import android.view.animation.AnimationUtils;
53import android.widget.FrameLayout;
54import android.widget.ScrollView;
55
56import java.util.List;
57
58/**
59 * NestedScrollView is just like {@link android.widget.ScrollView}, but it supports acting
60 * as both a nested scrolling parent and child on both new and old versions of Android.
61 * Nested scrolling is enabled by default.
62 */
63public class NestedScrollView extends FrameLayout implements NestedScrollingParent,
64        NestedScrollingChild, ScrollingView {
65    static final int ANIMATED_SCROLL_GAP = 250;
66
67    static final float MAX_SCROLL_FACTOR = 0.5f;
68
69    private static final String TAG = "NestedScrollView";
70
71    /**
72     * Interface definition for a callback to be invoked when the scroll
73     * X or Y positions of a view change.
74     *
75     * <p>This version of the interface works on all versions of Android, back to API v4.</p>
76     *
77     * @see #setOnScrollChangeListener(OnScrollChangeListener)
78     */
79    public interface OnScrollChangeListener {
80        /**
81         * Called when the scroll position of a view changes.
82         *
83         * @param v The view whose scroll position has changed.
84         * @param scrollX Current horizontal scroll origin.
85         * @param scrollY Current vertical scroll origin.
86         * @param oldScrollX Previous horizontal scroll origin.
87         * @param oldScrollY Previous vertical scroll origin.
88         */
89        void onScrollChange(NestedScrollView v, int scrollX, int scrollY,
90                int oldScrollX, int oldScrollY);
91    }
92
93    private long mLastScroll;
94
95    private final Rect mTempRect = new Rect();
96    private ScrollerCompat mScroller;
97    private EdgeEffectCompat mEdgeGlowTop;
98    private EdgeEffectCompat mEdgeGlowBottom;
99
100    /**
101     * Position of the last motion event.
102     */
103    private int mLastMotionY;
104
105    /**
106     * True when the layout has changed but the traversal has not come through yet.
107     * Ideally the view hierarchy would keep track of this for us.
108     */
109    private boolean mIsLayoutDirty = true;
110    private boolean mIsLaidOut = false;
111
112    /**
113     * The child to give focus to in the event that a child has requested focus while the
114     * layout is dirty. This prevents the scroll from being wrong if the child has not been
115     * laid out before requesting focus.
116     */
117    private View mChildToScrollTo = null;
118
119    /**
120     * True if the user is currently dragging this ScrollView around. This is
121     * not the same as 'is being flinged', which can be checked by
122     * mScroller.isFinished() (flinging begins when the user lifts his finger).
123     */
124    private boolean mIsBeingDragged = false;
125
126    /**
127     * Determines speed during touch scrolling
128     */
129    private VelocityTracker mVelocityTracker;
130
131    /**
132     * When set to true, the scroll view measure its child to make it fill the currently
133     * visible area.
134     */
135    private boolean mFillViewport;
136
137    /**
138     * Whether arrow scrolling is animated.
139     */
140    private boolean mSmoothScrollingEnabled = true;
141
142    private int mTouchSlop;
143    private int mMinimumVelocity;
144    private int mMaximumVelocity;
145
146    /**
147     * ID of the active pointer. This is used to retain consistency during
148     * drags/flings if multiple pointers are used.
149     */
150    private int mActivePointerId = INVALID_POINTER;
151
152    /**
153     * Used during scrolling to retrieve the new offset within the window.
154     */
155    private final int[] mScrollOffset = new int[2];
156    private final int[] mScrollConsumed = new int[2];
157    private int mNestedYOffset;
158
159    /**
160     * Sentinel value for no current active pointer.
161     * Used by {@link #mActivePointerId}.
162     */
163    private static final int INVALID_POINTER = -1;
164
165    private SavedState mSavedState;
166
167    private static final AccessibilityDelegate ACCESSIBILITY_DELEGATE = new AccessibilityDelegate();
168
169    private static final int[] SCROLLVIEW_STYLEABLE = new int[] {
170            android.R.attr.fillViewport
171    };
172
173    private final NestedScrollingParentHelper mParentHelper;
174    private final NestedScrollingChildHelper mChildHelper;
175
176    private float mVerticalScrollFactor;
177
178    private OnScrollChangeListener mOnScrollChangeListener;
179
180    public NestedScrollView(Context context) {
181        this(context, null);
182    }
183
184    public NestedScrollView(Context context, AttributeSet attrs) {
185        this(context, attrs, 0);
186    }
187
188    public NestedScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
189        super(context, attrs, defStyleAttr);
190        initScrollView();
191
192        final TypedArray a = context.obtainStyledAttributes(
193                attrs, SCROLLVIEW_STYLEABLE, defStyleAttr, 0);
194
195        setFillViewport(a.getBoolean(0, false));
196
197        a.recycle();
198
199        mParentHelper = new NestedScrollingParentHelper(this);
200        mChildHelper = new NestedScrollingChildHelper(this);
201
202        // ...because why else would you be using this widget?
203        setNestedScrollingEnabled(true);
204
205        ViewCompat.setAccessibilityDelegate(this, ACCESSIBILITY_DELEGATE);
206    }
207
208    // NestedScrollingChild
209
210    @Override
211    public void setNestedScrollingEnabled(boolean enabled) {
212        mChildHelper.setNestedScrollingEnabled(enabled);
213    }
214
215    @Override
216    public boolean isNestedScrollingEnabled() {
217        return mChildHelper.isNestedScrollingEnabled();
218    }
219
220    @Override
221    public boolean startNestedScroll(int axes) {
222        return mChildHelper.startNestedScroll(axes);
223    }
224
225    @Override
226    public void stopNestedScroll() {
227        mChildHelper.stopNestedScroll();
228    }
229
230    @Override
231    public boolean hasNestedScrollingParent() {
232        return mChildHelper.hasNestedScrollingParent();
233    }
234
235    @Override
236    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, int dxUnconsumed,
237            int dyUnconsumed, int[] offsetInWindow) {
238        return mChildHelper.dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed,
239                offsetInWindow);
240    }
241
242    @Override
243    public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) {
244        return mChildHelper.dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow);
245    }
246
247    @Override
248    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
249        return mChildHelper.dispatchNestedFling(velocityX, velocityY, consumed);
250    }
251
252    @Override
253    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
254        return mChildHelper.dispatchNestedPreFling(velocityX, velocityY);
255    }
256
257    // NestedScrollingParent
258
259    @Override
260    public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) {
261        return (nestedScrollAxes & ViewCompat.SCROLL_AXIS_VERTICAL) != 0;
262    }
263
264    @Override
265    public void onNestedScrollAccepted(View child, View target, int nestedScrollAxes) {
266        mParentHelper.onNestedScrollAccepted(child, target, nestedScrollAxes);
267        startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL);
268    }
269
270    @Override
271    public void onStopNestedScroll(View target) {
272        mParentHelper.onStopNestedScroll(target);
273        stopNestedScroll();
274    }
275
276    @Override
277    public void onNestedScroll(View target, int dxConsumed, int dyConsumed, int dxUnconsumed,
278            int dyUnconsumed) {
279        final int oldScrollY = getScrollY();
280        scrollBy(0, dyUnconsumed);
281        final int myConsumed = getScrollY() - oldScrollY;
282        final int myUnconsumed = dyUnconsumed - myConsumed;
283        dispatchNestedScroll(0, myConsumed, 0, myUnconsumed, null);
284    }
285
286    @Override
287    public void onNestedPreScroll(View target, int dx, int dy, int[] consumed) {
288        dispatchNestedPreScroll(dx, dy, consumed, null);
289    }
290
291    @Override
292    public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) {
293        if (!consumed) {
294            flingWithNestedDispatch((int) velocityY);
295            return true;
296        }
297        return false;
298    }
299
300    @Override
301    public boolean onNestedPreFling(View target, float velocityX, float velocityY) {
302        return dispatchNestedPreFling(velocityX, velocityY);
303    }
304
305    @Override
306    public int getNestedScrollAxes() {
307        return mParentHelper.getNestedScrollAxes();
308    }
309
310    // ScrollView import
311
312    public boolean shouldDelayChildPressedState() {
313        return true;
314    }
315
316    @Override
317    protected float getTopFadingEdgeStrength() {
318        if (getChildCount() == 0) {
319            return 0.0f;
320        }
321
322        final int length = getVerticalFadingEdgeLength();
323        final int scrollY = getScrollY();
324        if (scrollY < length) {
325            return scrollY / (float) length;
326        }
327
328        return 1.0f;
329    }
330
331    @Override
332    protected float getBottomFadingEdgeStrength() {
333        if (getChildCount() == 0) {
334            return 0.0f;
335        }
336
337        final int length = getVerticalFadingEdgeLength();
338        final int bottomEdge = getHeight() - getPaddingBottom();
339        final int span = getChildAt(0).getBottom() - getScrollY() - bottomEdge;
340        if (span < length) {
341            return span / (float) length;
342        }
343
344        return 1.0f;
345    }
346
347    /**
348     * @return The maximum amount this scroll view will scroll in response to
349     *   an arrow event.
350     */
351    public int getMaxScrollAmount() {
352        return (int) (MAX_SCROLL_FACTOR * getHeight());
353    }
354
355    private void initScrollView() {
356        mScroller = ScrollerCompat.create(getContext(), null);
357        setFocusable(true);
358        setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);
359        setWillNotDraw(false);
360        final ViewConfiguration configuration = ViewConfiguration.get(getContext());
361        mTouchSlop = configuration.getScaledTouchSlop();
362        mMinimumVelocity = configuration.getScaledMinimumFlingVelocity();
363        mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
364    }
365
366    @Override
367    public void addView(View child) {
368        if (getChildCount() > 0) {
369            throw new IllegalStateException("ScrollView can host only one direct child");
370        }
371
372        super.addView(child);
373    }
374
375    @Override
376    public void addView(View child, int index) {
377        if (getChildCount() > 0) {
378            throw new IllegalStateException("ScrollView can host only one direct child");
379        }
380
381        super.addView(child, index);
382    }
383
384    @Override
385    public void addView(View child, ViewGroup.LayoutParams params) {
386        if (getChildCount() > 0) {
387            throw new IllegalStateException("ScrollView can host only one direct child");
388        }
389
390        super.addView(child, params);
391    }
392
393    @Override
394    public void addView(View child, int index, ViewGroup.LayoutParams params) {
395        if (getChildCount() > 0) {
396            throw new IllegalStateException("ScrollView can host only one direct child");
397        }
398
399        super.addView(child, index, params);
400    }
401
402    /**
403     * Register a callback to be invoked when the scroll X or Y positions of
404     * this view change.
405     * <p>This version of the method works on all versions of Android, back to API v4.</p>
406     *
407     * @param l The listener to notify when the scroll X or Y position changes.
408     * @see android.view.View#getScrollX()
409     * @see android.view.View#getScrollY()
410     */
411    public void setOnScrollChangeListener(OnScrollChangeListener l) {
412        mOnScrollChangeListener = l;
413    }
414
415    /**
416     * @return Returns true this ScrollView can be scrolled
417     */
418    private boolean canScroll() {
419        View child = getChildAt(0);
420        if (child != null) {
421            int childHeight = child.getHeight();
422            return getHeight() < childHeight + getPaddingTop() + getPaddingBottom();
423        }
424        return false;
425    }
426
427    /**
428     * Indicates whether this ScrollView's content is stretched to fill the viewport.
429     *
430     * @return True if the content fills the viewport, false otherwise.
431     *
432     * @attr name android:fillViewport
433     */
434    public boolean isFillViewport() {
435        return mFillViewport;
436    }
437
438    /**
439     * Set whether this ScrollView should stretch its content height to fill the viewport or not.
440     *
441     * @param fillViewport True to stretch the content's height to the viewport's
442     *        boundaries, false otherwise.
443     *
444     * @attr name android:fillViewport
445     */
446    public void setFillViewport(boolean fillViewport) {
447        if (fillViewport != mFillViewport) {
448            mFillViewport = fillViewport;
449            requestLayout();
450        }
451    }
452
453    /**
454     * @return Whether arrow scrolling will animate its transition.
455     */
456    public boolean isSmoothScrollingEnabled() {
457        return mSmoothScrollingEnabled;
458    }
459
460    /**
461     * Set whether arrow scrolling will animate its transition.
462     * @param smoothScrollingEnabled whether arrow scrolling will animate its transition
463     */
464    public void setSmoothScrollingEnabled(boolean smoothScrollingEnabled) {
465        mSmoothScrollingEnabled = smoothScrollingEnabled;
466    }
467
468    @Override
469    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
470        super.onScrollChanged(l, t, oldl, oldt);
471
472        if (mOnScrollChangeListener != null) {
473            mOnScrollChangeListener.onScrollChange(this, l, t, oldl, oldt);
474        }
475    }
476
477    @Override
478    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
479        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
480
481        if (!mFillViewport) {
482            return;
483        }
484
485        final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
486        if (heightMode == MeasureSpec.UNSPECIFIED) {
487            return;
488        }
489
490        if (getChildCount() > 0) {
491            final View child = getChildAt(0);
492            int height = getMeasuredHeight();
493            if (child.getMeasuredHeight() < height) {
494                final FrameLayout.LayoutParams lp = (LayoutParams) child.getLayoutParams();
495
496                int childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
497                        getPaddingLeft() + getPaddingRight(), lp.width);
498                height -= getPaddingTop();
499                height -= getPaddingBottom();
500                int childHeightMeasureSpec =
501                        MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
502
503                child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
504            }
505        }
506    }
507
508    @Override
509    public boolean dispatchKeyEvent(KeyEvent event) {
510        // Let the focused view and/or our descendants get the key first
511        return super.dispatchKeyEvent(event) || executeKeyEvent(event);
512    }
513
514    /**
515     * You can call this function yourself to have the scroll view perform
516     * scrolling from a key event, just as if the event had been dispatched to
517     * it by the view hierarchy.
518     *
519     * @param event The key event to execute.
520     * @return Return true if the event was handled, else false.
521     */
522    public boolean executeKeyEvent(KeyEvent event) {
523        mTempRect.setEmpty();
524
525        if (!canScroll()) {
526            if (isFocused() && event.getKeyCode() != KeyEvent.KEYCODE_BACK) {
527                View currentFocused = findFocus();
528                if (currentFocused == this) currentFocused = null;
529                View nextFocused = FocusFinder.getInstance().findNextFocus(this,
530                        currentFocused, View.FOCUS_DOWN);
531                return nextFocused != null
532                        && nextFocused != this
533                        && nextFocused.requestFocus(View.FOCUS_DOWN);
534            }
535            return false;
536        }
537
538        boolean handled = false;
539        if (event.getAction() == KeyEvent.ACTION_DOWN) {
540            switch (event.getKeyCode()) {
541                case KeyEvent.KEYCODE_DPAD_UP:
542                    if (!event.isAltPressed()) {
543                        handled = arrowScroll(View.FOCUS_UP);
544                    } else {
545                        handled = fullScroll(View.FOCUS_UP);
546                    }
547                    break;
548                case KeyEvent.KEYCODE_DPAD_DOWN:
549                    if (!event.isAltPressed()) {
550                        handled = arrowScroll(View.FOCUS_DOWN);
551                    } else {
552                        handled = fullScroll(View.FOCUS_DOWN);
553                    }
554                    break;
555                case KeyEvent.KEYCODE_SPACE:
556                    pageScroll(event.isShiftPressed() ? View.FOCUS_UP : View.FOCUS_DOWN);
557                    break;
558            }
559        }
560
561        return handled;
562    }
563
564    private boolean inChild(int x, int y) {
565        if (getChildCount() > 0) {
566            final int scrollY = getScrollY();
567            final View child = getChildAt(0);
568            return !(y < child.getTop() - scrollY
569                    || y >= child.getBottom() - scrollY
570                    || x < child.getLeft()
571                    || x >= child.getRight());
572        }
573        return false;
574    }
575
576    private void initOrResetVelocityTracker() {
577        if (mVelocityTracker == null) {
578            mVelocityTracker = VelocityTracker.obtain();
579        } else {
580            mVelocityTracker.clear();
581        }
582    }
583
584    private void initVelocityTrackerIfNotExists() {
585        if (mVelocityTracker == null) {
586            mVelocityTracker = VelocityTracker.obtain();
587        }
588    }
589
590    private void recycleVelocityTracker() {
591        if (mVelocityTracker != null) {
592            mVelocityTracker.recycle();
593            mVelocityTracker = null;
594        }
595    }
596
597    @Override
598    public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
599        if (disallowIntercept) {
600            recycleVelocityTracker();
601        }
602        super.requestDisallowInterceptTouchEvent(disallowIntercept);
603    }
604
605
606    @Override
607    public boolean onInterceptTouchEvent(MotionEvent ev) {
608        /*
609         * This method JUST determines whether we want to intercept the motion.
610         * If we return true, onMotionEvent will be called and we do the actual
611         * scrolling there.
612         */
613
614        /*
615        * Shortcut the most recurring case: the user is in the dragging
616        * state and he is moving his finger.  We want to intercept this
617        * motion.
618        */
619        final int action = ev.getAction();
620        if ((action == MotionEvent.ACTION_MOVE) && (mIsBeingDragged)) {
621            return true;
622        }
623
624        switch (action & MotionEventCompat.ACTION_MASK) {
625            case MotionEvent.ACTION_MOVE: {
626                /*
627                 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
628                 * whether the user has moved far enough from his original down touch.
629                 */
630
631                /*
632                * Locally do absolute value. mLastMotionY is set to the y value
633                * of the down event.
634                */
635                final int activePointerId = mActivePointerId;
636                if (activePointerId == INVALID_POINTER) {
637                    // If we don't have a valid id, the touch down wasn't on content.
638                    break;
639                }
640
641                final int pointerIndex = ev.findPointerIndex(activePointerId);
642                if (pointerIndex == -1) {
643                    Log.e(TAG, "Invalid pointerId=" + activePointerId
644                            + " in onInterceptTouchEvent");
645                    break;
646                }
647
648                final int y = (int) ev.getY(pointerIndex);
649                final int yDiff = Math.abs(y - mLastMotionY);
650                if (yDiff > mTouchSlop
651                        && (getNestedScrollAxes() & ViewCompat.SCROLL_AXIS_VERTICAL) == 0) {
652                    mIsBeingDragged = true;
653                    mLastMotionY = y;
654                    initVelocityTrackerIfNotExists();
655                    mVelocityTracker.addMovement(ev);
656                    mNestedYOffset = 0;
657                    final ViewParent parent = getParent();
658                    if (parent != null) {
659                        parent.requestDisallowInterceptTouchEvent(true);
660                    }
661                }
662                break;
663            }
664
665            case MotionEvent.ACTION_DOWN: {
666                final int y = (int) ev.getY();
667                if (!inChild((int) ev.getX(), (int) y)) {
668                    mIsBeingDragged = false;
669                    recycleVelocityTracker();
670                    break;
671                }
672
673                /*
674                 * Remember location of down touch.
675                 * ACTION_DOWN always refers to pointer index 0.
676                 */
677                mLastMotionY = y;
678                mActivePointerId = ev.getPointerId(0);
679
680                initOrResetVelocityTracker();
681                mVelocityTracker.addMovement(ev);
682                /*
683                 * If being flinged and user touches the screen, initiate drag;
684                 * otherwise don't. mScroller.isFinished should be false when
685                 * being flinged. We need to call computeScrollOffset() first so that
686                 * isFinished() is correct.
687                */
688                mScroller.computeScrollOffset();
689                mIsBeingDragged = !mScroller.isFinished();
690                startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL);
691                break;
692            }
693
694            case MotionEvent.ACTION_CANCEL:
695            case MotionEvent.ACTION_UP:
696                /* Release the drag */
697                mIsBeingDragged = false;
698                mActivePointerId = INVALID_POINTER;
699                recycleVelocityTracker();
700                if (mScroller.springBack(getScrollX(), getScrollY(), 0, 0, 0, getScrollRange())) {
701                    ViewCompat.postInvalidateOnAnimation(this);
702                }
703                stopNestedScroll();
704                break;
705            case MotionEventCompat.ACTION_POINTER_UP:
706                onSecondaryPointerUp(ev);
707                break;
708        }
709
710        /*
711        * The only time we want to intercept motion events is if we are in the
712        * drag mode.
713        */
714        return mIsBeingDragged;
715    }
716
717    @Override
718    public boolean onTouchEvent(MotionEvent ev) {
719        initVelocityTrackerIfNotExists();
720
721        MotionEvent vtev = MotionEvent.obtain(ev);
722
723        final int actionMasked = MotionEventCompat.getActionMasked(ev);
724
725        if (actionMasked == MotionEvent.ACTION_DOWN) {
726            mNestedYOffset = 0;
727        }
728        vtev.offsetLocation(0, mNestedYOffset);
729
730        switch (actionMasked) {
731            case MotionEvent.ACTION_DOWN: {
732                if (getChildCount() == 0) {
733                    return false;
734                }
735                if ((mIsBeingDragged = !mScroller.isFinished())) {
736                    final ViewParent parent = getParent();
737                    if (parent != null) {
738                        parent.requestDisallowInterceptTouchEvent(true);
739                    }
740                }
741
742                /*
743                 * If being flinged and user touches, stop the fling. isFinished
744                 * will be false if being flinged.
745                 */
746                if (!mScroller.isFinished()) {
747                    mScroller.abortAnimation();
748                }
749
750                // Remember where the motion event started
751                mLastMotionY = (int) ev.getY();
752                mActivePointerId = ev.getPointerId(0);
753                startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL);
754                break;
755            }
756            case MotionEvent.ACTION_MOVE:
757                final int activePointerIndex = ev.findPointerIndex(mActivePointerId);
758                if (activePointerIndex == -1) {
759                    Log.e(TAG, "Invalid pointerId=" + mActivePointerId + " in onTouchEvent");
760                    break;
761                }
762
763                final int y = (int) ev.getY(activePointerIndex);
764                int deltaY = mLastMotionY - y;
765                if (dispatchNestedPreScroll(0, deltaY, mScrollConsumed, mScrollOffset)) {
766                    deltaY -= mScrollConsumed[1];
767                    vtev.offsetLocation(0, mScrollOffset[1]);
768                    mNestedYOffset += mScrollOffset[1];
769                }
770                if (!mIsBeingDragged && Math.abs(deltaY) > mTouchSlop) {
771                    final ViewParent parent = getParent();
772                    if (parent != null) {
773                        parent.requestDisallowInterceptTouchEvent(true);
774                    }
775                    mIsBeingDragged = true;
776                    if (deltaY > 0) {
777                        deltaY -= mTouchSlop;
778                    } else {
779                        deltaY += mTouchSlop;
780                    }
781                }
782                if (mIsBeingDragged) {
783                    // Scroll to follow the motion event
784                    mLastMotionY = y - mScrollOffset[1];
785
786                    final int oldY = getScrollY();
787                    final int range = getScrollRange();
788                    final int overscrollMode = ViewCompat.getOverScrollMode(this);
789                    boolean canOverscroll = overscrollMode == ViewCompat.OVER_SCROLL_ALWAYS ||
790                            (overscrollMode == ViewCompat.OVER_SCROLL_IF_CONTENT_SCROLLS &&
791                                    range > 0);
792
793                    // Calling overScrollByCompat will call onOverScrolled, which
794                    // calls onScrollChanged if applicable.
795                    if (overScrollByCompat(0, deltaY, 0, getScrollY(), 0, range, 0,
796                            0, true) && !hasNestedScrollingParent()) {
797                        // Break our velocity if we hit a scroll barrier.
798                        mVelocityTracker.clear();
799                    }
800
801                    final int scrolledDeltaY = getScrollY() - oldY;
802                    final int unconsumedY = deltaY - scrolledDeltaY;
803                    if (dispatchNestedScroll(0, scrolledDeltaY, 0, unconsumedY, mScrollOffset)) {
804                        mLastMotionY -= mScrollOffset[1];
805                        vtev.offsetLocation(0, mScrollOffset[1]);
806                        mNestedYOffset += mScrollOffset[1];
807                    } else if (canOverscroll) {
808                        ensureGlows();
809                        final int pulledToY = oldY + deltaY;
810                        if (pulledToY < 0) {
811                            mEdgeGlowTop.onPull((float) deltaY / getHeight(),
812                                    ev.getX(activePointerIndex) / getWidth());
813                            if (!mEdgeGlowBottom.isFinished()) {
814                                mEdgeGlowBottom.onRelease();
815                            }
816                        } else if (pulledToY > range) {
817                            mEdgeGlowBottom.onPull((float) deltaY / getHeight(),
818                                    1.f - ev.getX(activePointerIndex)
819                                            / getWidth());
820                            if (!mEdgeGlowTop.isFinished()) {
821                                mEdgeGlowTop.onRelease();
822                            }
823                        }
824                        if (mEdgeGlowTop != null
825                                && (!mEdgeGlowTop.isFinished() || !mEdgeGlowBottom.isFinished())) {
826                            ViewCompat.postInvalidateOnAnimation(this);
827                        }
828                    }
829                }
830                break;
831            case MotionEvent.ACTION_UP:
832                if (mIsBeingDragged) {
833                    final VelocityTracker velocityTracker = mVelocityTracker;
834                    velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
835                    int initialVelocity = (int) VelocityTrackerCompat.getYVelocity(velocityTracker,
836                            mActivePointerId);
837
838                    if ((Math.abs(initialVelocity) > mMinimumVelocity)) {
839                        flingWithNestedDispatch(-initialVelocity);
840                    } else if (mScroller.springBack(getScrollX(), getScrollY(), 0, 0, 0,
841                            getScrollRange())) {
842                        ViewCompat.postInvalidateOnAnimation(this);
843                    }
844                }
845                mActivePointerId = INVALID_POINTER;
846                endDrag();
847                break;
848            case MotionEvent.ACTION_CANCEL:
849                if (mIsBeingDragged && getChildCount() > 0) {
850                    if (mScroller.springBack(getScrollX(), getScrollY(), 0, 0, 0,
851                            getScrollRange())) {
852                        ViewCompat.postInvalidateOnAnimation(this);
853                    }
854                }
855                mActivePointerId = INVALID_POINTER;
856                endDrag();
857                break;
858            case MotionEventCompat.ACTION_POINTER_DOWN: {
859                final int index = MotionEventCompat.getActionIndex(ev);
860                mLastMotionY = (int) ev.getY(index);
861                mActivePointerId = ev.getPointerId(index);
862                break;
863            }
864            case MotionEventCompat.ACTION_POINTER_UP:
865                onSecondaryPointerUp(ev);
866                mLastMotionY = (int) ev.getY(ev.findPointerIndex(mActivePointerId));
867                break;
868        }
869
870        if (mVelocityTracker != null) {
871            mVelocityTracker.addMovement(vtev);
872        }
873        vtev.recycle();
874        return true;
875    }
876
877    private void onSecondaryPointerUp(MotionEvent ev) {
878        final int pointerIndex = (ev.getAction() & MotionEventCompat.ACTION_POINTER_INDEX_MASK) >>
879                MotionEventCompat.ACTION_POINTER_INDEX_SHIFT;
880        final int pointerId = ev.getPointerId(pointerIndex);
881        if (pointerId == mActivePointerId) {
882            // This was our active pointer going up. Choose a new
883            // active pointer and adjust accordingly.
884            // TODO: Make this decision more intelligent.
885            final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
886            mLastMotionY = (int) ev.getY(newPointerIndex);
887            mActivePointerId = ev.getPointerId(newPointerIndex);
888            if (mVelocityTracker != null) {
889                mVelocityTracker.clear();
890            }
891        }
892    }
893
894    public boolean onGenericMotionEvent(MotionEvent event) {
895        if ((event.getSource() & InputDeviceCompat.SOURCE_CLASS_POINTER) != 0) {
896            switch (event.getAction()) {
897                case MotionEventCompat.ACTION_SCROLL: {
898                    if (!mIsBeingDragged) {
899                        final float vscroll = MotionEventCompat.getAxisValue(event,
900                                MotionEventCompat.AXIS_VSCROLL);
901                        if (vscroll != 0) {
902                            final int delta = (int) (vscroll * getVerticalScrollFactorCompat());
903                            final int range = getScrollRange();
904                            int oldScrollY = getScrollY();
905                            int newScrollY = oldScrollY - delta;
906                            if (newScrollY < 0) {
907                                newScrollY = 0;
908                            } else if (newScrollY > range) {
909                                newScrollY = range;
910                            }
911                            if (newScrollY != oldScrollY) {
912                                super.scrollTo(getScrollX(), newScrollY);
913                                return true;
914                            }
915                        }
916                    }
917                }
918            }
919        }
920        return false;
921    }
922
923    private float getVerticalScrollFactorCompat() {
924        if (mVerticalScrollFactor == 0) {
925            TypedValue outValue = new TypedValue();
926            final Context context = getContext();
927            if (!context.getTheme().resolveAttribute(
928                    android.R.attr.listPreferredItemHeight, outValue, true)) {
929                throw new IllegalStateException(
930                        "Expected theme to define listPreferredItemHeight.");
931            }
932            mVerticalScrollFactor = outValue.getDimension(
933                    context.getResources().getDisplayMetrics());
934        }
935        return mVerticalScrollFactor;
936    }
937
938    @Override
939    protected void onOverScrolled(int scrollX, int scrollY,
940            boolean clampedX, boolean clampedY) {
941        super.scrollTo(scrollX, scrollY);
942    }
943
944    boolean overScrollByCompat(int deltaX, int deltaY,
945            int scrollX, int scrollY,
946            int scrollRangeX, int scrollRangeY,
947            int maxOverScrollX, int maxOverScrollY,
948            boolean isTouchEvent) {
949        final int overScrollMode = ViewCompat.getOverScrollMode(this);
950        final boolean canScrollHorizontal =
951                computeHorizontalScrollRange() > computeHorizontalScrollExtent();
952        final boolean canScrollVertical =
953                computeVerticalScrollRange() > computeVerticalScrollExtent();
954        final boolean overScrollHorizontal = overScrollMode == ViewCompat.OVER_SCROLL_ALWAYS ||
955                (overScrollMode == ViewCompat.OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
956        final boolean overScrollVertical = overScrollMode == ViewCompat.OVER_SCROLL_ALWAYS ||
957                (overScrollMode == ViewCompat.OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
958
959        int newScrollX = scrollX + deltaX;
960        if (!overScrollHorizontal) {
961            maxOverScrollX = 0;
962        }
963
964        int newScrollY = scrollY + deltaY;
965        if (!overScrollVertical) {
966            maxOverScrollY = 0;
967        }
968
969        // Clamp values if at the limits and record
970        final int left = -maxOverScrollX;
971        final int right = maxOverScrollX + scrollRangeX;
972        final int top = -maxOverScrollY;
973        final int bottom = maxOverScrollY + scrollRangeY;
974
975        boolean clampedX = false;
976        if (newScrollX > right) {
977            newScrollX = right;
978            clampedX = true;
979        } else if (newScrollX < left) {
980            newScrollX = left;
981            clampedX = true;
982        }
983
984        boolean clampedY = false;
985        if (newScrollY > bottom) {
986            newScrollY = bottom;
987            clampedY = true;
988        } else if (newScrollY < top) {
989            newScrollY = top;
990            clampedY = true;
991        }
992
993        if (clampedY) {
994            mScroller.springBack(newScrollX, newScrollY, 0, 0, 0, getScrollRange());
995        }
996
997        onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
998
999        return clampedX || clampedY;
1000    }
1001
1002    private int getScrollRange() {
1003        int scrollRange = 0;
1004        if (getChildCount() > 0) {
1005            View child = getChildAt(0);
1006            scrollRange = Math.max(0,
1007                    child.getHeight() - (getHeight() - getPaddingBottom() - getPaddingTop()));
1008        }
1009        return scrollRange;
1010    }
1011
1012    /**
1013     * <p>
1014     * Finds the next focusable component that fits in the specified bounds.
1015     * </p>
1016     *
1017     * @param topFocus look for a candidate is the one at the top of the bounds
1018     *                 if topFocus is true, or at the bottom of the bounds if topFocus is
1019     *                 false
1020     * @param top      the top offset of the bounds in which a focusable must be
1021     *                 found
1022     * @param bottom   the bottom offset of the bounds in which a focusable must
1023     *                 be found
1024     * @return the next focusable component in the bounds or null if none can
1025     *         be found
1026     */
1027    private View findFocusableViewInBounds(boolean topFocus, int top, int bottom) {
1028
1029        List<View> focusables = getFocusables(View.FOCUS_FORWARD);
1030        View focusCandidate = null;
1031
1032        /*
1033         * A fully contained focusable is one where its top is below the bound's
1034         * top, and its bottom is above the bound's bottom. A partially
1035         * contained focusable is one where some part of it is within the
1036         * bounds, but it also has some part that is not within bounds.  A fully contained
1037         * focusable is preferred to a partially contained focusable.
1038         */
1039        boolean foundFullyContainedFocusable = false;
1040
1041        int count = focusables.size();
1042        for (int i = 0; i < count; i++) {
1043            View view = focusables.get(i);
1044            int viewTop = view.getTop();
1045            int viewBottom = view.getBottom();
1046
1047            if (top < viewBottom && viewTop < bottom) {
1048                /*
1049                 * the focusable is in the target area, it is a candidate for
1050                 * focusing
1051                 */
1052
1053                final boolean viewIsFullyContained = (top < viewTop) &&
1054                        (viewBottom < bottom);
1055
1056                if (focusCandidate == null) {
1057                    /* No candidate, take this one */
1058                    focusCandidate = view;
1059                    foundFullyContainedFocusable = viewIsFullyContained;
1060                } else {
1061                    final boolean viewIsCloserToBoundary =
1062                            (topFocus && viewTop < focusCandidate.getTop()) ||
1063                                    (!topFocus && viewBottom > focusCandidate
1064                                            .getBottom());
1065
1066                    if (foundFullyContainedFocusable) {
1067                        if (viewIsFullyContained && viewIsCloserToBoundary) {
1068                            /*
1069                             * We're dealing with only fully contained views, so
1070                             * it has to be closer to the boundary to beat our
1071                             * candidate
1072                             */
1073                            focusCandidate = view;
1074                        }
1075                    } else {
1076                        if (viewIsFullyContained) {
1077                            /* Any fully contained view beats a partially contained view */
1078                            focusCandidate = view;
1079                            foundFullyContainedFocusable = true;
1080                        } else if (viewIsCloserToBoundary) {
1081                            /*
1082                             * Partially contained view beats another partially
1083                             * contained view if it's closer
1084                             */
1085                            focusCandidate = view;
1086                        }
1087                    }
1088                }
1089            }
1090        }
1091
1092        return focusCandidate;
1093    }
1094
1095    /**
1096     * <p>Handles scrolling in response to a "page up/down" shortcut press. This
1097     * method will scroll the view by one page up or down and give the focus
1098     * to the topmost/bottommost component in the new visible area. If no
1099     * component is a good candidate for focus, this scrollview reclaims the
1100     * focus.</p>
1101     *
1102     * @param direction the scroll direction: {@link android.view.View#FOCUS_UP}
1103     *                  to go one page up or
1104     *                  {@link android.view.View#FOCUS_DOWN} to go one page down
1105     * @return true if the key event is consumed by this method, false otherwise
1106     */
1107    public boolean pageScroll(int direction) {
1108        boolean down = direction == View.FOCUS_DOWN;
1109        int height = getHeight();
1110
1111        if (down) {
1112            mTempRect.top = getScrollY() + height;
1113            int count = getChildCount();
1114            if (count > 0) {
1115                View view = getChildAt(count - 1);
1116                if (mTempRect.top + height > view.getBottom()) {
1117                    mTempRect.top = view.getBottom() - height;
1118                }
1119            }
1120        } else {
1121            mTempRect.top = getScrollY() - height;
1122            if (mTempRect.top < 0) {
1123                mTempRect.top = 0;
1124            }
1125        }
1126        mTempRect.bottom = mTempRect.top + height;
1127
1128        return scrollAndFocus(direction, mTempRect.top, mTempRect.bottom);
1129    }
1130
1131    /**
1132     * <p>Handles scrolling in response to a "home/end" shortcut press. This
1133     * method will scroll the view to the top or bottom and give the focus
1134     * to the topmost/bottommost component in the new visible area. If no
1135     * component is a good candidate for focus, this scrollview reclaims the
1136     * focus.</p>
1137     *
1138     * @param direction the scroll direction: {@link android.view.View#FOCUS_UP}
1139     *                  to go the top of the view or
1140     *                  {@link android.view.View#FOCUS_DOWN} to go the bottom
1141     * @return true if the key event is consumed by this method, false otherwise
1142     */
1143    public boolean fullScroll(int direction) {
1144        boolean down = direction == View.FOCUS_DOWN;
1145        int height = getHeight();
1146
1147        mTempRect.top = 0;
1148        mTempRect.bottom = height;
1149
1150        if (down) {
1151            int count = getChildCount();
1152            if (count > 0) {
1153                View view = getChildAt(count - 1);
1154                mTempRect.bottom = view.getBottom() + getPaddingBottom();
1155                mTempRect.top = mTempRect.bottom - height;
1156            }
1157        }
1158
1159        return scrollAndFocus(direction, mTempRect.top, mTempRect.bottom);
1160    }
1161
1162    /**
1163     * <p>Scrolls the view to make the area defined by <code>top</code> and
1164     * <code>bottom</code> visible. This method attempts to give the focus
1165     * to a component visible in this area. If no component can be focused in
1166     * the new visible area, the focus is reclaimed by this ScrollView.</p>
1167     *
1168     * @param direction the scroll direction: {@link android.view.View#FOCUS_UP}
1169     *                  to go upward, {@link android.view.View#FOCUS_DOWN} to downward
1170     * @param top       the top offset of the new area to be made visible
1171     * @param bottom    the bottom offset of the new area to be made visible
1172     * @return true if the key event is consumed by this method, false otherwise
1173     */
1174    private boolean scrollAndFocus(int direction, int top, int bottom) {
1175        boolean handled = true;
1176
1177        int height = getHeight();
1178        int containerTop = getScrollY();
1179        int containerBottom = containerTop + height;
1180        boolean up = direction == View.FOCUS_UP;
1181
1182        View newFocused = findFocusableViewInBounds(up, top, bottom);
1183        if (newFocused == null) {
1184            newFocused = this;
1185        }
1186
1187        if (top >= containerTop && bottom <= containerBottom) {
1188            handled = false;
1189        } else {
1190            int delta = up ? (top - containerTop) : (bottom - containerBottom);
1191            doScrollY(delta);
1192        }
1193
1194        if (newFocused != findFocus()) newFocused.requestFocus(direction);
1195
1196        return handled;
1197    }
1198
1199    /**
1200     * Handle scrolling in response to an up or down arrow click.
1201     *
1202     * @param direction The direction corresponding to the arrow key that was
1203     *                  pressed
1204     * @return True if we consumed the event, false otherwise
1205     */
1206    public boolean arrowScroll(int direction) {
1207
1208        View currentFocused = findFocus();
1209        if (currentFocused == this) currentFocused = null;
1210
1211        View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, direction);
1212
1213        final int maxJump = getMaxScrollAmount();
1214
1215        if (nextFocused != null && isWithinDeltaOfScreen(nextFocused, maxJump, getHeight())) {
1216            nextFocused.getDrawingRect(mTempRect);
1217            offsetDescendantRectToMyCoords(nextFocused, mTempRect);
1218            int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
1219            doScrollY(scrollDelta);
1220            nextFocused.requestFocus(direction);
1221        } else {
1222            // no new focus
1223            int scrollDelta = maxJump;
1224
1225            if (direction == View.FOCUS_UP && getScrollY() < scrollDelta) {
1226                scrollDelta = getScrollY();
1227            } else if (direction == View.FOCUS_DOWN) {
1228                if (getChildCount() > 0) {
1229                    int daBottom = getChildAt(0).getBottom();
1230                    int screenBottom = getScrollY() + getHeight() - getPaddingBottom();
1231                    if (daBottom - screenBottom < maxJump) {
1232                        scrollDelta = daBottom - screenBottom;
1233                    }
1234                }
1235            }
1236            if (scrollDelta == 0) {
1237                return false;
1238            }
1239            doScrollY(direction == View.FOCUS_DOWN ? scrollDelta : -scrollDelta);
1240        }
1241
1242        if (currentFocused != null && currentFocused.isFocused()
1243                && isOffScreen(currentFocused)) {
1244            // previously focused item still has focus and is off screen, give
1245            // it up (take it back to ourselves)
1246            // (also, need to temporarily force FOCUS_BEFORE_DESCENDANTS so we are
1247            // sure to
1248            // get it)
1249            final int descendantFocusability = getDescendantFocusability();  // save
1250            setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
1251            requestFocus();
1252            setDescendantFocusability(descendantFocusability);  // restore
1253        }
1254        return true;
1255    }
1256
1257    /**
1258     * @return whether the descendant of this scroll view is scrolled off
1259     *  screen.
1260     */
1261    private boolean isOffScreen(View descendant) {
1262        return !isWithinDeltaOfScreen(descendant, 0, getHeight());
1263    }
1264
1265    /**
1266     * @return whether the descendant of this scroll view is within delta
1267     *  pixels of being on the screen.
1268     */
1269    private boolean isWithinDeltaOfScreen(View descendant, int delta, int height) {
1270        descendant.getDrawingRect(mTempRect);
1271        offsetDescendantRectToMyCoords(descendant, mTempRect);
1272
1273        return (mTempRect.bottom + delta) >= getScrollY()
1274                && (mTempRect.top - delta) <= (getScrollY() + height);
1275    }
1276
1277    /**
1278     * Smooth scroll by a Y delta
1279     *
1280     * @param delta the number of pixels to scroll by on the Y axis
1281     */
1282    private void doScrollY(int delta) {
1283        if (delta != 0) {
1284            if (mSmoothScrollingEnabled) {
1285                smoothScrollBy(0, delta);
1286            } else {
1287                scrollBy(0, delta);
1288            }
1289        }
1290    }
1291
1292    /**
1293     * Like {@link View#scrollBy}, but scroll smoothly instead of immediately.
1294     *
1295     * @param dx the number of pixels to scroll by on the X axis
1296     * @param dy the number of pixels to scroll by on the Y axis
1297     */
1298    public final void smoothScrollBy(int dx, int dy) {
1299        if (getChildCount() == 0) {
1300            // Nothing to do.
1301            return;
1302        }
1303        long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll;
1304        if (duration > ANIMATED_SCROLL_GAP) {
1305            final int height = getHeight() - getPaddingBottom() - getPaddingTop();
1306            final int bottom = getChildAt(0).getHeight();
1307            final int maxY = Math.max(0, bottom - height);
1308            final int scrollY = getScrollY();
1309            dy = Math.max(0, Math.min(scrollY + dy, maxY)) - scrollY;
1310
1311            mScroller.startScroll(getScrollX(), scrollY, 0, dy);
1312            ViewCompat.postInvalidateOnAnimation(this);
1313        } else {
1314            if (!mScroller.isFinished()) {
1315                mScroller.abortAnimation();
1316            }
1317            scrollBy(dx, dy);
1318        }
1319        mLastScroll = AnimationUtils.currentAnimationTimeMillis();
1320    }
1321
1322    /**
1323     * Like {@link #scrollTo}, but scroll smoothly instead of immediately.
1324     *
1325     * @param x the position where to scroll on the X axis
1326     * @param y the position where to scroll on the Y axis
1327     */
1328    public final void smoothScrollTo(int x, int y) {
1329        smoothScrollBy(x - getScrollX(), y - getScrollY());
1330    }
1331
1332    /**
1333     * <p>The scroll range of a scroll view is the overall height of all of its
1334     * children.</p>
1335     * @hide
1336     */
1337    @Override
1338    public int computeVerticalScrollRange() {
1339        final int count = getChildCount();
1340        final int contentHeight = getHeight() - getPaddingBottom() - getPaddingTop();
1341        if (count == 0) {
1342            return contentHeight;
1343        }
1344
1345        int scrollRange = getChildAt(0).getBottom();
1346        final int scrollY = getScrollY();
1347        final int overscrollBottom = Math.max(0, scrollRange - contentHeight);
1348        if (scrollY < 0) {
1349            scrollRange -= scrollY;
1350        } else if (scrollY > overscrollBottom) {
1351            scrollRange += scrollY - overscrollBottom;
1352        }
1353
1354        return scrollRange;
1355    }
1356
1357    /** @hide */
1358    @Override
1359    public int computeVerticalScrollOffset() {
1360        return Math.max(0, super.computeVerticalScrollOffset());
1361    }
1362
1363    /** @hide */
1364    @Override
1365    public int computeVerticalScrollExtent() {
1366        return super.computeVerticalScrollExtent();
1367    }
1368
1369    /** @hide */
1370    @Override
1371    public int computeHorizontalScrollRange() {
1372        return super.computeHorizontalScrollRange();
1373    }
1374
1375    /** @hide */
1376    @Override
1377    public int computeHorizontalScrollOffset() {
1378        return super.computeHorizontalScrollOffset();
1379    }
1380
1381    /** @hide */
1382    @Override
1383    public int computeHorizontalScrollExtent() {
1384        return super.computeHorizontalScrollExtent();
1385    }
1386
1387    @Override
1388    protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) {
1389        ViewGroup.LayoutParams lp = child.getLayoutParams();
1390
1391        int childWidthMeasureSpec;
1392        int childHeightMeasureSpec;
1393
1394        childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, getPaddingLeft()
1395                + getPaddingRight(), lp.width);
1396
1397        childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
1398
1399        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1400    }
1401
1402    @Override
1403    protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed,
1404            int parentHeightMeasureSpec, int heightUsed) {
1405        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
1406
1407        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
1408                getPaddingLeft() + getPaddingRight() + lp.leftMargin + lp.rightMargin
1409                        + widthUsed, lp.width);
1410        final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
1411                lp.topMargin + lp.bottomMargin, MeasureSpec.UNSPECIFIED);
1412
1413        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1414    }
1415
1416    @Override
1417    public void computeScroll() {
1418        if (mScroller.computeScrollOffset()) {
1419            int oldX = getScrollX();
1420            int oldY = getScrollY();
1421            int x = mScroller.getCurrX();
1422            int y = mScroller.getCurrY();
1423
1424            if (oldX != x || oldY != y) {
1425                final int range = getScrollRange();
1426                final int overscrollMode = ViewCompat.getOverScrollMode(this);
1427                final boolean canOverscroll = overscrollMode == ViewCompat.OVER_SCROLL_ALWAYS ||
1428                        (overscrollMode == ViewCompat.OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0);
1429
1430                overScrollByCompat(x - oldX, y - oldY, oldX, oldY, 0, range,
1431                        0, 0, false);
1432
1433                if (canOverscroll) {
1434                    ensureGlows();
1435                    if (y <= 0 && oldY > 0) {
1436                        mEdgeGlowTop.onAbsorb((int) mScroller.getCurrVelocity());
1437                    } else if (y >= range && oldY < range) {
1438                        mEdgeGlowBottom.onAbsorb((int) mScroller.getCurrVelocity());
1439                    }
1440                }
1441            }
1442        }
1443    }
1444
1445    /**
1446     * Scrolls the view to the given child.
1447     *
1448     * @param child the View to scroll to
1449     */
1450    private void scrollToChild(View child) {
1451        child.getDrawingRect(mTempRect);
1452
1453        /* Offset from child's local coordinates to ScrollView coordinates */
1454        offsetDescendantRectToMyCoords(child, mTempRect);
1455
1456        int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
1457
1458        if (scrollDelta != 0) {
1459            scrollBy(0, scrollDelta);
1460        }
1461    }
1462
1463    /**
1464     * If rect is off screen, scroll just enough to get it (or at least the
1465     * first screen size chunk of it) on screen.
1466     *
1467     * @param rect      The rectangle.
1468     * @param immediate True to scroll immediately without animation
1469     * @return true if scrolling was performed
1470     */
1471    private boolean scrollToChildRect(Rect rect, boolean immediate) {
1472        final int delta = computeScrollDeltaToGetChildRectOnScreen(rect);
1473        final boolean scroll = delta != 0;
1474        if (scroll) {
1475            if (immediate) {
1476                scrollBy(0, delta);
1477            } else {
1478                smoothScrollBy(0, delta);
1479            }
1480        }
1481        return scroll;
1482    }
1483
1484    /**
1485     * Compute the amount to scroll in the Y direction in order to get
1486     * a rectangle completely on the screen (or, if taller than the screen,
1487     * at least the first screen size chunk of it).
1488     *
1489     * @param rect The rect.
1490     * @return The scroll delta.
1491     */
1492    protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) {
1493        if (getChildCount() == 0) return 0;
1494
1495        int height = getHeight();
1496        int screenTop = getScrollY();
1497        int screenBottom = screenTop + height;
1498
1499        int fadingEdge = getVerticalFadingEdgeLength();
1500
1501        // leave room for top fading edge as long as rect isn't at very top
1502        if (rect.top > 0) {
1503            screenTop += fadingEdge;
1504        }
1505
1506        // leave room for bottom fading edge as long as rect isn't at very bottom
1507        if (rect.bottom < getChildAt(0).getHeight()) {
1508            screenBottom -= fadingEdge;
1509        }
1510
1511        int scrollYDelta = 0;
1512
1513        if (rect.bottom > screenBottom && rect.top > screenTop) {
1514            // need to move down to get it in view: move down just enough so
1515            // that the entire rectangle is in view (or at least the first
1516            // screen size chunk).
1517
1518            if (rect.height() > height) {
1519                // just enough to get screen size chunk on
1520                scrollYDelta += (rect.top - screenTop);
1521            } else {
1522                // get entire rect at bottom of screen
1523                scrollYDelta += (rect.bottom - screenBottom);
1524            }
1525
1526            // make sure we aren't scrolling beyond the end of our content
1527            int bottom = getChildAt(0).getBottom();
1528            int distanceToBottom = bottom - screenBottom;
1529            scrollYDelta = Math.min(scrollYDelta, distanceToBottom);
1530
1531        } else if (rect.top < screenTop && rect.bottom < screenBottom) {
1532            // need to move up to get it in view: move up just enough so that
1533            // entire rectangle is in view (or at least the first screen
1534            // size chunk of it).
1535
1536            if (rect.height() > height) {
1537                // screen size chunk
1538                scrollYDelta -= (screenBottom - rect.bottom);
1539            } else {
1540                // entire rect at top
1541                scrollYDelta -= (screenTop - rect.top);
1542            }
1543
1544            // make sure we aren't scrolling any further than the top our content
1545            scrollYDelta = Math.max(scrollYDelta, -getScrollY());
1546        }
1547        return scrollYDelta;
1548    }
1549
1550    @Override
1551    public void requestChildFocus(View child, View focused) {
1552        if (!mIsLayoutDirty) {
1553            scrollToChild(focused);
1554        } else {
1555            // The child may not be laid out yet, we can't compute the scroll yet
1556            mChildToScrollTo = focused;
1557        }
1558        super.requestChildFocus(child, focused);
1559    }
1560
1561
1562    /**
1563     * When looking for focus in children of a scroll view, need to be a little
1564     * more careful not to give focus to something that is scrolled off screen.
1565     *
1566     * This is more expensive than the default {@link android.view.ViewGroup}
1567     * implementation, otherwise this behavior might have been made the default.
1568     */
1569    @Override
1570    protected boolean onRequestFocusInDescendants(int direction,
1571            Rect previouslyFocusedRect) {
1572
1573        // convert from forward / backward notation to up / down / left / right
1574        // (ugh).
1575        if (direction == View.FOCUS_FORWARD) {
1576            direction = View.FOCUS_DOWN;
1577        } else if (direction == View.FOCUS_BACKWARD) {
1578            direction = View.FOCUS_UP;
1579        }
1580
1581        final View nextFocus = previouslyFocusedRect == null ?
1582                FocusFinder.getInstance().findNextFocus(this, null, direction) :
1583                FocusFinder.getInstance().findNextFocusFromRect(this,
1584                        previouslyFocusedRect, direction);
1585
1586        if (nextFocus == null) {
1587            return false;
1588        }
1589
1590        if (isOffScreen(nextFocus)) {
1591            return false;
1592        }
1593
1594        return nextFocus.requestFocus(direction, previouslyFocusedRect);
1595    }
1596
1597    @Override
1598    public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
1599            boolean immediate) {
1600        // offset into coordinate space of this scroll view
1601        rectangle.offset(child.getLeft() - child.getScrollX(),
1602                child.getTop() - child.getScrollY());
1603
1604        return scrollToChildRect(rectangle, immediate);
1605    }
1606
1607    @Override
1608    public void requestLayout() {
1609        mIsLayoutDirty = true;
1610        super.requestLayout();
1611    }
1612
1613    @Override
1614    protected void onLayout(boolean changed, int l, int t, int r, int b) {
1615        super.onLayout(changed, l, t, r, b);
1616        mIsLayoutDirty = false;
1617        // Give a child focus if it needs it
1618        if (mChildToScrollTo != null && isViewDescendantOf(mChildToScrollTo, this)) {
1619            scrollToChild(mChildToScrollTo);
1620        }
1621        mChildToScrollTo = null;
1622
1623        if (!mIsLaidOut) {
1624            if (mSavedState != null) {
1625                scrollTo(getScrollX(), mSavedState.scrollPosition);
1626                mSavedState = null;
1627            } // mScrollY default value is "0"
1628
1629            final int childHeight = (getChildCount() > 0) ? getChildAt(0).getMeasuredHeight() : 0;
1630            final int scrollRange = Math.max(0,
1631                    childHeight - (b - t - getPaddingBottom() - getPaddingTop()));
1632
1633            // Don't forget to clamp
1634            if (getScrollY() > scrollRange) {
1635                scrollTo(getScrollX(), scrollRange);
1636            } else if (getScrollY() < 0) {
1637                scrollTo(getScrollX(), 0);
1638            }
1639        }
1640
1641        // Calling this with the present values causes it to re-claim them
1642        scrollTo(getScrollX(), getScrollY());
1643        mIsLaidOut = true;
1644    }
1645
1646    @Override
1647    public void onAttachedToWindow() {
1648        super.onAttachedToWindow();
1649
1650        mIsLaidOut = false;
1651    }
1652
1653    @Override
1654    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
1655        super.onSizeChanged(w, h, oldw, oldh);
1656
1657        View currentFocused = findFocus();
1658        if (null == currentFocused || this == currentFocused)
1659            return;
1660
1661        // If the currently-focused view was visible on the screen when the
1662        // screen was at the old height, then scroll the screen to make that
1663        // view visible with the new screen height.
1664        if (isWithinDeltaOfScreen(currentFocused, 0, oldh)) {
1665            currentFocused.getDrawingRect(mTempRect);
1666            offsetDescendantRectToMyCoords(currentFocused, mTempRect);
1667            int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
1668            doScrollY(scrollDelta);
1669        }
1670    }
1671
1672    /**
1673     * Return true if child is a descendant of parent, (or equal to the parent).
1674     */
1675    private static boolean isViewDescendantOf(View child, View parent) {
1676        if (child == parent) {
1677            return true;
1678        }
1679
1680        final ViewParent theParent = child.getParent();
1681        return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1682    }
1683
1684    /**
1685     * Fling the scroll view
1686     *
1687     * @param velocityY The initial velocity in the Y direction. Positive
1688     *                  numbers mean that the finger/cursor is moving down the screen,
1689     *                  which means we want to scroll towards the top.
1690     */
1691    public void fling(int velocityY) {
1692        if (getChildCount() > 0) {
1693            int height = getHeight() - getPaddingBottom() - getPaddingTop();
1694            int bottom = getChildAt(0).getHeight();
1695
1696            mScroller.fling(getScrollX(), getScrollY(), 0, velocityY, 0, 0, 0,
1697                    Math.max(0, bottom - height), 0, height/2);
1698
1699            ViewCompat.postInvalidateOnAnimation(this);
1700        }
1701    }
1702
1703    private void flingWithNestedDispatch(int velocityY) {
1704        final int scrollY = getScrollY();
1705        final boolean canFling = (scrollY > 0 || velocityY > 0) &&
1706                (scrollY < getScrollRange() || velocityY < 0);
1707        if (!dispatchNestedPreFling(0, velocityY)) {
1708            dispatchNestedFling(0, velocityY, canFling);
1709            if (canFling) {
1710                fling(velocityY);
1711            }
1712        }
1713    }
1714
1715    private void endDrag() {
1716        mIsBeingDragged = false;
1717
1718        recycleVelocityTracker();
1719        stopNestedScroll();
1720
1721        if (mEdgeGlowTop != null) {
1722            mEdgeGlowTop.onRelease();
1723            mEdgeGlowBottom.onRelease();
1724        }
1725    }
1726
1727    /**
1728     * {@inheritDoc}
1729     *
1730     * <p>This version also clamps the scrolling to the bounds of our child.
1731     */
1732    @Override
1733    public void scrollTo(int x, int y) {
1734        // we rely on the fact the View.scrollBy calls scrollTo.
1735        if (getChildCount() > 0) {
1736            View child = getChildAt(0);
1737            x = clamp(x, getWidth() - getPaddingRight() - getPaddingLeft(), child.getWidth());
1738            y = clamp(y, getHeight() - getPaddingBottom() - getPaddingTop(), child.getHeight());
1739            if (x != getScrollX() || y != getScrollY()) {
1740                super.scrollTo(x, y);
1741            }
1742        }
1743    }
1744
1745    private void ensureGlows() {
1746        if (ViewCompat.getOverScrollMode(this) != ViewCompat.OVER_SCROLL_NEVER) {
1747            if (mEdgeGlowTop == null) {
1748                Context context = getContext();
1749                mEdgeGlowTop = new EdgeEffectCompat(context);
1750                mEdgeGlowBottom = new EdgeEffectCompat(context);
1751            }
1752        } else {
1753            mEdgeGlowTop = null;
1754            mEdgeGlowBottom = null;
1755        }
1756    }
1757
1758    @Override
1759    public void draw(Canvas canvas) {
1760        super.draw(canvas);
1761        if (mEdgeGlowTop != null) {
1762            final int scrollY = getScrollY();
1763            if (!mEdgeGlowTop.isFinished()) {
1764                final int restoreCount = canvas.save();
1765                final int width = getWidth() - getPaddingLeft() - getPaddingRight();
1766
1767                canvas.translate(getPaddingLeft(), Math.min(0, scrollY));
1768                mEdgeGlowTop.setSize(width, getHeight());
1769                if (mEdgeGlowTop.draw(canvas)) {
1770                    ViewCompat.postInvalidateOnAnimation(this);
1771                }
1772                canvas.restoreToCount(restoreCount);
1773            }
1774            if (!mEdgeGlowBottom.isFinished()) {
1775                final int restoreCount = canvas.save();
1776                final int width = getWidth() - getPaddingLeft() - getPaddingRight();
1777                final int height = getHeight();
1778
1779                canvas.translate(-width + getPaddingLeft(),
1780                        Math.max(getScrollRange(), scrollY) + height);
1781                canvas.rotate(180, width, 0);
1782                mEdgeGlowBottom.setSize(width, height);
1783                if (mEdgeGlowBottom.draw(canvas)) {
1784                    ViewCompat.postInvalidateOnAnimation(this);
1785                }
1786                canvas.restoreToCount(restoreCount);
1787            }
1788        }
1789    }
1790
1791    private static int clamp(int n, int my, int child) {
1792        if (my >= child || n < 0) {
1793            /* my >= child is this case:
1794             *                    |--------------- me ---------------|
1795             *     |------ child ------|
1796             * or
1797             *     |--------------- me ---------------|
1798             *            |------ child ------|
1799             * or
1800             *     |--------------- me ---------------|
1801             *                                  |------ child ------|
1802             *
1803             * n < 0 is this case:
1804             *     |------ me ------|
1805             *                    |-------- child --------|
1806             *     |-- mScrollX --|
1807             */
1808            return 0;
1809        }
1810        if ((my+n) > child) {
1811            /* this case:
1812             *                    |------ me ------|
1813             *     |------ child ------|
1814             *     |-- mScrollX --|
1815             */
1816            return child-my;
1817        }
1818        return n;
1819    }
1820
1821    @Override
1822    protected void onRestoreInstanceState(Parcelable state) {
1823        if (!(state instanceof SavedState)) {
1824            super.onRestoreInstanceState(state);
1825            return;
1826        }
1827
1828        SavedState ss = (SavedState) state;
1829        super.onRestoreInstanceState(ss.getSuperState());
1830        mSavedState = ss;
1831        requestLayout();
1832    }
1833
1834    @Override
1835    protected Parcelable onSaveInstanceState() {
1836        Parcelable superState = super.onSaveInstanceState();
1837        SavedState ss = new SavedState(superState);
1838        ss.scrollPosition = getScrollY();
1839        return ss;
1840    }
1841
1842    static class SavedState extends BaseSavedState {
1843        public int scrollPosition;
1844
1845        SavedState(Parcelable superState) {
1846            super(superState);
1847        }
1848
1849        public SavedState(Parcel source) {
1850            super(source);
1851            scrollPosition = source.readInt();
1852        }
1853
1854        @Override
1855        public void writeToParcel(Parcel dest, int flags) {
1856            super.writeToParcel(dest, flags);
1857            dest.writeInt(scrollPosition);
1858        }
1859
1860        @Override
1861        public String toString() {
1862            return "HorizontalScrollView.SavedState{"
1863                    + Integer.toHexString(System.identityHashCode(this))
1864                    + " scrollPosition=" + scrollPosition + "}";
1865        }
1866
1867        public static final Parcelable.Creator<SavedState> CREATOR
1868                = new Parcelable.Creator<SavedState>() {
1869            @Override
1870            public SavedState createFromParcel(Parcel in) {
1871                return new SavedState(in);
1872            }
1873
1874            @Override
1875            public SavedState[] newArray(int size) {
1876                return new SavedState[size];
1877            }
1878        };
1879    }
1880
1881    static class AccessibilityDelegate extends AccessibilityDelegateCompat {
1882        @Override
1883        public boolean performAccessibilityAction(View host, int action, Bundle arguments) {
1884            if (super.performAccessibilityAction(host, action, arguments)) {
1885                return true;
1886            }
1887            final NestedScrollView nsvHost = (NestedScrollView) host;
1888            if (!nsvHost.isEnabled()) {
1889                return false;
1890            }
1891            switch (action) {
1892                case AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD: {
1893                    final int viewportHeight = nsvHost.getHeight() - nsvHost.getPaddingBottom()
1894                            - nsvHost.getPaddingTop();
1895                    final int targetScrollY = Math.min(nsvHost.getScrollY() + viewportHeight,
1896                            nsvHost.getScrollRange());
1897                    if (targetScrollY != nsvHost.getScrollY()) {
1898                        nsvHost.smoothScrollTo(0, targetScrollY);
1899                        return true;
1900                    }
1901                }
1902                return false;
1903                case AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD: {
1904                    final int viewportHeight = nsvHost.getHeight() - nsvHost.getPaddingBottom()
1905                            - nsvHost.getPaddingTop();
1906                    final int targetScrollY = Math.max(nsvHost.getScrollY() - viewportHeight, 0);
1907                    if (targetScrollY != nsvHost.getScrollY()) {
1908                        nsvHost.smoothScrollTo(0, targetScrollY);
1909                        return true;
1910                    }
1911                }
1912                return false;
1913            }
1914            return false;
1915        }
1916
1917        @Override
1918        public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfoCompat info) {
1919            super.onInitializeAccessibilityNodeInfo(host, info);
1920            final NestedScrollView nsvHost = (NestedScrollView) host;
1921            info.setClassName(ScrollView.class.getName());
1922            if (nsvHost.isEnabled()) {
1923                final int scrollRange = nsvHost.getScrollRange();
1924                if (scrollRange > 0) {
1925                    info.setScrollable(true);
1926                    if (nsvHost.getScrollY() > 0) {
1927                        info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD);
1928                    }
1929                    if (nsvHost.getScrollY() < scrollRange) {
1930                        info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD);
1931                    }
1932                }
1933            }
1934        }
1935
1936        @Override
1937        public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
1938            super.onInitializeAccessibilityEvent(host, event);
1939            final NestedScrollView nsvHost = (NestedScrollView) host;
1940            event.setClassName(ScrollView.class.getName());
1941            final AccessibilityRecordCompat record = AccessibilityEventCompat.asRecord(event);
1942            final boolean scrollable = nsvHost.getScrollRange() > 0;
1943            record.setScrollable(scrollable);
1944            record.setScrollX(nsvHost.getScrollX());
1945            record.setScrollY(nsvHost.getScrollY());
1946            record.setMaxScrollX(nsvHost.getScrollX());
1947            record.setMaxScrollY(nsvHost.getScrollRange());
1948        }
1949    }
1950}
1951