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