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