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