ScrollView.java revision a174d7a0d5475dbae2b48f7359abf1637a882896
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
17package android.widget;
18
19import android.view.ViewDebug;
20import com.android.internal.R;
21
22import android.content.Context;
23import android.content.res.Resources;
24import android.content.res.TypedArray;
25import android.graphics.Canvas;
26import android.graphics.Rect;
27import android.graphics.drawable.Drawable;
28import android.os.StrictMode;
29import android.util.AttributeSet;
30import android.view.FocusFinder;
31import android.view.KeyEvent;
32import android.view.MotionEvent;
33import android.view.VelocityTracker;
34import android.view.View;
35import android.view.ViewConfiguration;
36import android.view.ViewGroup;
37import android.view.ViewParent;
38import android.view.animation.AnimationUtils;
39
40import java.util.List;
41
42/**
43 * Layout container for a view hierarchy that can be scrolled by the user,
44 * allowing it to be larger than the physical display.  A ScrollView
45 * is a {@link FrameLayout}, meaning you should place one child in it
46 * containing the entire contents to scroll; this child may itself be a layout
47 * manager with a complex hierarchy of objects.  A child that is often used
48 * is a {@link LinearLayout} in a vertical orientation, presenting a vertical
49 * array of top-level items that the user can scroll through.
50 *
51 * <p>The {@link TextView} class also
52 * takes care of its own scrolling, so does not require a ScrollView, but
53 * using the two together is possible to achieve the effect of a text view
54 * within a larger container.
55 *
56 * <p>ScrollView only supports vertical scrolling.
57 *
58 * @attr ref android.R.styleable#ScrollView_fillViewport
59 */
60public class ScrollView extends FrameLayout {
61    static final int ANIMATED_SCROLL_GAP = 250;
62
63    static final float MAX_SCROLL_FACTOR = 0.5f;
64
65
66    private long mLastScroll;
67
68    private final Rect mTempRect = new Rect();
69    private OverScroller mScroller;
70    private EdgeGlow mEdgeGlowTop;
71    private EdgeGlow mEdgeGlowBottom;
72
73    /**
74     * Flag to indicate that we are moving focus ourselves. This is so the
75     * code that watches for focus changes initiated outside this ScrollView
76     * knows that it does not have to do anything.
77     */
78    private boolean mScrollViewMovedFocus;
79
80    /**
81     * Position of the last motion event.
82     */
83    private float mLastMotionY;
84
85    /**
86     * True when the layout has changed but the traversal has not come through yet.
87     * Ideally the view hierarchy would keep track of this for us.
88     */
89    private boolean mIsLayoutDirty = true;
90
91    /**
92     * The child to give focus to in the event that a child has requested focus while the
93     * layout is dirty. This prevents the scroll from being wrong if the child has not been
94     * laid out before requesting focus.
95     */
96    private View mChildToScrollTo = null;
97
98    /**
99     * True if the user is currently dragging this ScrollView around. This is
100     * not the same as 'is being flinged', which can be checked by
101     * mScroller.isFinished() (flinging begins when the user lifts his finger).
102     */
103    private boolean mIsBeingDragged = false;
104
105    /**
106     * Determines speed during touch scrolling
107     */
108    private VelocityTracker mVelocityTracker;
109
110    /**
111     * When set to true, the scroll view measure its child to make it fill the currently
112     * visible area.
113     */
114    @ViewDebug.ExportedProperty(category = "layout")
115    private boolean mFillViewport;
116
117    /**
118     * Whether arrow scrolling is animated.
119     */
120    private boolean mSmoothScrollingEnabled = true;
121
122    private int mTouchSlop;
123    private int mMinimumVelocity;
124    private int mMaximumVelocity;
125
126    private int mOverscrollDistance;
127    private int mOverflingDistance;
128
129    /**
130     * ID of the active pointer. This is used to retain consistency during
131     * drags/flings if multiple pointers are used.
132     */
133    private int mActivePointerId = INVALID_POINTER;
134
135    /**
136     * The StrictMode "critical time span" objects to catch animation
137     * stutters.  Non-null when a time-sensitive animation is
138     * in-flight.  Must call finish() on them when done animating.
139     * These are no-ops on user builds.
140     */
141    private StrictMode.Span mScrollStrictSpan = null;  // aka "drag"
142    private StrictMode.Span mFlingStrictSpan = null;
143
144    /**
145     * Sentinel value for no current active pointer.
146     * Used by {@link #mActivePointerId}.
147     */
148    private static final int INVALID_POINTER = -1;
149
150    public ScrollView(Context context) {
151        this(context, null);
152    }
153
154    public ScrollView(Context context, AttributeSet attrs) {
155        this(context, attrs, com.android.internal.R.attr.scrollViewStyle);
156    }
157
158    public ScrollView(Context context, AttributeSet attrs, int defStyle) {
159        super(context, attrs, defStyle);
160        initScrollView();
161
162        TypedArray a =
163            context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.ScrollView, defStyle, 0);
164
165        setFillViewport(a.getBoolean(R.styleable.ScrollView_fillViewport, false));
166
167        a.recycle();
168    }
169
170    @Override
171    protected float getTopFadingEdgeStrength() {
172        if (getChildCount() == 0) {
173            return 0.0f;
174        }
175
176        final int length = getVerticalFadingEdgeLength();
177        if (mScrollY < length) {
178            return mScrollY / (float) length;
179        }
180
181        return 1.0f;
182    }
183
184    @Override
185    protected float getBottomFadingEdgeStrength() {
186        if (getChildCount() == 0) {
187            return 0.0f;
188        }
189
190        final int length = getVerticalFadingEdgeLength();
191        final int bottomEdge = getHeight() - mPaddingBottom;
192        final int span = getChildAt(0).getBottom() - mScrollY - bottomEdge;
193        if (span < length) {
194            return span / (float) length;
195        }
196
197        return 1.0f;
198    }
199
200    /**
201     * @return The maximum amount this scroll view will scroll in response to
202     *   an arrow event.
203     */
204    public int getMaxScrollAmount() {
205        return (int) (MAX_SCROLL_FACTOR * (mBottom - mTop));
206    }
207
208
209    private void initScrollView() {
210        mScroller = new OverScroller(getContext());
211        setFocusable(true);
212        setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);
213        setWillNotDraw(false);
214        final ViewConfiguration configuration = ViewConfiguration.get(mContext);
215        mTouchSlop = configuration.getScaledTouchSlop();
216        mMinimumVelocity = configuration.getScaledMinimumFlingVelocity();
217        mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
218        mOverscrollDistance = configuration.getScaledOverscrollDistance();
219        mOverflingDistance = configuration.getScaledOverflingDistance();
220    }
221
222    @Override
223    public void addView(View child) {
224        if (getChildCount() > 0) {
225            throw new IllegalStateException("ScrollView can host only one direct child");
226        }
227
228        super.addView(child);
229    }
230
231    @Override
232    public void addView(View child, int index) {
233        if (getChildCount() > 0) {
234            throw new IllegalStateException("ScrollView can host only one direct child");
235        }
236
237        super.addView(child, index);
238    }
239
240    @Override
241    public void addView(View child, ViewGroup.LayoutParams params) {
242        if (getChildCount() > 0) {
243            throw new IllegalStateException("ScrollView can host only one direct child");
244        }
245
246        super.addView(child, params);
247    }
248
249    @Override
250    public void addView(View child, int index, ViewGroup.LayoutParams params) {
251        if (getChildCount() > 0) {
252            throw new IllegalStateException("ScrollView can host only one direct child");
253        }
254
255        super.addView(child, index, params);
256    }
257
258    /**
259     * @return Returns true this ScrollView can be scrolled
260     */
261    private boolean canScroll() {
262        View child = getChildAt(0);
263        if (child != null) {
264            int childHeight = child.getHeight();
265            return getHeight() < childHeight + mPaddingTop + mPaddingBottom;
266        }
267        return false;
268    }
269
270    /**
271     * Indicates whether this ScrollView's content is stretched to fill the viewport.
272     *
273     * @return True if the content fills the viewport, false otherwise.
274     *
275     * @attr ref android.R.styleable#ScrollView_fillViewport
276     */
277    public boolean isFillViewport() {
278        return mFillViewport;
279    }
280
281    /**
282     * Indicates this ScrollView whether it should stretch its content height to fill
283     * the viewport or not.
284     *
285     * @param fillViewport True to stretch the content's height to the viewport's
286     *        boundaries, false otherwise.
287     *
288     * @attr ref android.R.styleable#ScrollView_fillViewport
289     */
290    public void setFillViewport(boolean fillViewport) {
291        if (fillViewport != mFillViewport) {
292            mFillViewport = fillViewport;
293            requestLayout();
294        }
295    }
296
297    /**
298     * @return Whether arrow scrolling will animate its transition.
299     */
300    public boolean isSmoothScrollingEnabled() {
301        return mSmoothScrollingEnabled;
302    }
303
304    /**
305     * Set whether arrow scrolling will animate its transition.
306     * @param smoothScrollingEnabled whether arrow scrolling will animate its transition
307     */
308    public void setSmoothScrollingEnabled(boolean smoothScrollingEnabled) {
309        mSmoothScrollingEnabled = smoothScrollingEnabled;
310    }
311
312    @Override
313    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
314        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
315
316        if (!mFillViewport) {
317            return;
318        }
319
320        final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
321        if (heightMode == MeasureSpec.UNSPECIFIED) {
322            return;
323        }
324
325        if (getChildCount() > 0) {
326            final View child = getChildAt(0);
327            int height = getMeasuredHeight();
328            if (child.getMeasuredHeight() < height) {
329                final FrameLayout.LayoutParams lp = (LayoutParams) child.getLayoutParams();
330
331                int childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
332                        mPaddingLeft + mPaddingRight, lp.width);
333                height -= mPaddingTop;
334                height -= mPaddingBottom;
335                int childHeightMeasureSpec =
336                        MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
337
338                child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
339            }
340        }
341    }
342
343    @Override
344    public boolean dispatchKeyEvent(KeyEvent event) {
345        // Let the focused view and/or our descendants get the key first
346        return super.dispatchKeyEvent(event) || executeKeyEvent(event);
347    }
348
349    /**
350     * You can call this function yourself to have the scroll view perform
351     * scrolling from a key event, just as if the event had been dispatched to
352     * it by the view hierarchy.
353     *
354     * @param event The key event to execute.
355     * @return Return true if the event was handled, else false.
356     */
357    public boolean executeKeyEvent(KeyEvent event) {
358        mTempRect.setEmpty();
359
360        if (!canScroll()) {
361            if (isFocused() && event.getKeyCode() != KeyEvent.KEYCODE_BACK) {
362                View currentFocused = findFocus();
363                if (currentFocused == this) currentFocused = null;
364                View nextFocused = FocusFinder.getInstance().findNextFocus(this,
365                        currentFocused, View.FOCUS_DOWN);
366                return nextFocused != null
367                        && nextFocused != this
368                        && nextFocused.requestFocus(View.FOCUS_DOWN);
369            }
370            return false;
371        }
372
373        boolean handled = false;
374        if (event.getAction() == KeyEvent.ACTION_DOWN) {
375            switch (event.getKeyCode()) {
376                case KeyEvent.KEYCODE_DPAD_UP:
377                    if (!event.isAltPressed()) {
378                        handled = arrowScroll(View.FOCUS_UP);
379                    } else {
380                        handled = fullScroll(View.FOCUS_UP);
381                    }
382                    break;
383                case KeyEvent.KEYCODE_DPAD_DOWN:
384                    if (!event.isAltPressed()) {
385                        handled = arrowScroll(View.FOCUS_DOWN);
386                    } else {
387                        handled = fullScroll(View.FOCUS_DOWN);
388                    }
389                    break;
390                case KeyEvent.KEYCODE_SPACE:
391                    pageScroll(event.isShiftPressed() ? View.FOCUS_UP : View.FOCUS_DOWN);
392                    break;
393            }
394        }
395
396        return handled;
397    }
398
399    private boolean inChild(int x, int y) {
400        if (getChildCount() > 0) {
401            final int scrollY = mScrollY;
402            final View child = getChildAt(0);
403            return !(y < child.getTop() - scrollY
404                    || y >= child.getBottom() - scrollY
405                    || x < child.getLeft()
406                    || x >= child.getRight());
407        }
408        return false;
409    }
410
411    @Override
412    public boolean onInterceptTouchEvent(MotionEvent ev) {
413        /*
414         * This method JUST determines whether we want to intercept the motion.
415         * If we return true, onMotionEvent will be called and we do the actual
416         * scrolling there.
417         */
418
419        /*
420        * Shortcut the most recurring case: the user is in the dragging
421        * state and he is moving his finger.  We want to intercept this
422        * motion.
423        */
424        final int action = ev.getAction();
425        if ((action == MotionEvent.ACTION_MOVE) && (mIsBeingDragged)) {
426            return true;
427        }
428
429        switch (action & MotionEvent.ACTION_MASK) {
430            case MotionEvent.ACTION_MOVE: {
431                /*
432                 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
433                 * whether the user has moved far enough from his original down touch.
434                 */
435
436                /*
437                * Locally do absolute value. mLastMotionY is set to the y value
438                * of the down event.
439                */
440                final int activePointerId = mActivePointerId;
441                if (activePointerId == INVALID_POINTER) {
442                    // If we don't have a valid id, the touch down wasn't on content.
443                    break;
444                }
445
446                final int pointerIndex = ev.findPointerIndex(activePointerId);
447                final float y = ev.getY(pointerIndex);
448                final int yDiff = (int) Math.abs(y - mLastMotionY);
449                if (yDiff > mTouchSlop) {
450                    mIsBeingDragged = true;
451                    mLastMotionY = y;
452                    if (mScrollStrictSpan == null) {
453                        mScrollStrictSpan = StrictMode.enterCriticalSpan("ScrollView-scroll");
454                    }
455                }
456                break;
457            }
458
459            case MotionEvent.ACTION_DOWN: {
460                final float y = ev.getY();
461                if (!inChild((int) ev.getX(), (int) y)) {
462                    mIsBeingDragged = false;
463                    break;
464                }
465
466                /*
467                 * Remember location of down touch.
468                 * ACTION_DOWN always refers to pointer index 0.
469                 */
470                mLastMotionY = y;
471                mActivePointerId = ev.getPointerId(0);
472
473                /*
474                * If being flinged and user touches the screen, initiate drag;
475                * otherwise don't.  mScroller.isFinished should be false when
476                * being flinged.
477                */
478                mIsBeingDragged = !mScroller.isFinished();
479                if (mIsBeingDragged && mScrollStrictSpan == null) {
480                    mScrollStrictSpan = StrictMode.enterCriticalSpan("ScrollView-scroll");
481                }
482                break;
483            }
484
485            case MotionEvent.ACTION_CANCEL:
486            case MotionEvent.ACTION_UP:
487                /* Release the drag */
488                mIsBeingDragged = false;
489                mActivePointerId = INVALID_POINTER;
490                if (mScroller.springBack(mScrollX, mScrollY, 0, 0, 0, getScrollRange())) {
491                    invalidate();
492                }
493                break;
494            case MotionEvent.ACTION_POINTER_UP:
495                onSecondaryPointerUp(ev);
496                break;
497        }
498
499        /*
500        * The only time we want to intercept motion events is if we are in the
501        * drag mode.
502        */
503        return mIsBeingDragged;
504    }
505
506    @Override
507    public boolean onTouchEvent(MotionEvent ev) {
508
509        if (ev.getAction() == MotionEvent.ACTION_DOWN && ev.getEdgeFlags() != 0) {
510            // Don't handle edge touches immediately -- they may actually belong to one of our
511            // descendants.
512            return false;
513        }
514
515        if (mVelocityTracker == null) {
516            mVelocityTracker = VelocityTracker.obtain();
517        }
518        mVelocityTracker.addMovement(ev);
519
520        final int action = ev.getAction();
521
522        switch (action & MotionEvent.ACTION_MASK) {
523            case MotionEvent.ACTION_DOWN: {
524                final float y = ev.getY();
525                mIsBeingDragged = true;
526
527                /*
528                 * If being flinged and user touches, stop the fling. isFinished
529                 * will be false if being flinged.
530                 */
531                if (!mScroller.isFinished()) {
532                    mScroller.abortAnimation();
533                    if (mFlingStrictSpan != null) {
534                        mFlingStrictSpan.finish();
535                        mFlingStrictSpan = null;
536                    }
537                }
538
539                // Remember where the motion event started
540                mLastMotionY = y;
541                mActivePointerId = ev.getPointerId(0);
542                break;
543            }
544            case MotionEvent.ACTION_MOVE:
545                if (mIsBeingDragged) {
546                    // Scroll to follow the motion event
547                    final int activePointerIndex = ev.findPointerIndex(mActivePointerId);
548                    final float y = ev.getY(activePointerIndex);
549                    final int deltaY = (int) (mLastMotionY - y);
550                    mLastMotionY = y;
551
552                    final int oldX = mScrollX;
553                    final int oldY = mScrollY;
554                    final int range = getScrollRange();
555                    if (overScrollBy(0, deltaY, 0, mScrollY, 0, range,
556                            0, mOverscrollDistance, true)) {
557                        // Break our velocity if we hit a scroll barrier.
558                        mVelocityTracker.clear();
559                    }
560                    onScrollChanged(mScrollX, mScrollY, oldX, oldY);
561
562                    final int overscrollMode = getOverScrollMode();
563                    if (overscrollMode == OVER_SCROLL_ALWAYS ||
564                            (overscrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0)) {
565                        final int pulledToY = oldY + deltaY;
566                        if (pulledToY < 0) {
567                            mEdgeGlowTop.onPull((float) deltaY / getHeight());
568                            if (!mEdgeGlowBottom.isFinished()) {
569                                mEdgeGlowBottom.onRelease();
570                            }
571                        } else if (pulledToY > range) {
572                            mEdgeGlowBottom.onPull((float) deltaY / getHeight());
573                            if (!mEdgeGlowTop.isFinished()) {
574                                mEdgeGlowTop.onRelease();
575                            }
576                        }
577                        if (mEdgeGlowTop != null
578                                && (!mEdgeGlowTop.isFinished() || !mEdgeGlowBottom.isFinished())) {
579                            invalidate();
580                        }
581                    }
582                }
583                break;
584            case MotionEvent.ACTION_UP:
585                if (mIsBeingDragged) {
586                    final VelocityTracker velocityTracker = mVelocityTracker;
587                    velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
588                    int initialVelocity = (int) velocityTracker.getYVelocity(mActivePointerId);
589
590                    if (getChildCount() > 0) {
591                        if ((Math.abs(initialVelocity) > mMinimumVelocity)) {
592                            fling(-initialVelocity);
593                        } else {
594                            final int bottom = getScrollRange();
595                            if (mScroller.springBack(mScrollX, mScrollY, 0, 0, 0, bottom)) {
596                                invalidate();
597                            }
598                        }
599                    }
600
601                    mActivePointerId = INVALID_POINTER;
602                    endDrag();
603                }
604                break;
605            case MotionEvent.ACTION_CANCEL:
606                if (mIsBeingDragged && getChildCount() > 0) {
607                    if (mScroller.springBack(mScrollX, mScrollY, 0, 0, 0, getScrollRange())) {
608                        invalidate();
609                    }
610                    mActivePointerId = INVALID_POINTER;
611                    endDrag();
612                }
613                break;
614            case MotionEvent.ACTION_POINTER_UP:
615                onSecondaryPointerUp(ev);
616                break;
617        }
618        return true;
619    }
620
621    private void onSecondaryPointerUp(MotionEvent ev) {
622        final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
623                MotionEvent.ACTION_POINTER_INDEX_SHIFT;
624        final int pointerId = ev.getPointerId(pointerIndex);
625        if (pointerId == mActivePointerId) {
626            // This was our active pointer going up. Choose a new
627            // active pointer and adjust accordingly.
628            // TODO: Make this decision more intelligent.
629            final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
630            mLastMotionY = ev.getY(newPointerIndex);
631            mActivePointerId = ev.getPointerId(newPointerIndex);
632            if (mVelocityTracker != null) {
633                mVelocityTracker.clear();
634            }
635        }
636    }
637
638    @Override
639    protected void onOverScrolled(int scrollX, int scrollY,
640            boolean clampedX, boolean clampedY) {
641        // Treat animating scrolls differently; see #computeScroll() for why.
642        if (!mScroller.isFinished()) {
643            mScrollX = scrollX;
644            mScrollY = scrollY;
645            if (clampedY) {
646                mScroller.springBack(mScrollX, mScrollY, 0, 0, 0, getScrollRange());
647            }
648        } else {
649            super.scrollTo(scrollX, scrollY);
650        }
651        awakenScrollBars();
652    }
653
654    private int getScrollRange() {
655        int scrollRange = 0;
656        if (getChildCount() > 0) {
657            View child = getChildAt(0);
658            scrollRange = Math.max(0,
659                    child.getHeight() - (getHeight() - mPaddingBottom - mPaddingTop));
660        }
661        return scrollRange;
662    }
663
664    /**
665     * <p>
666     * Finds the next focusable component that fits in this View's bounds
667     * (excluding fading edges) pretending that this View's top is located at
668     * the parameter top.
669     * </p>
670     *
671     * @param topFocus           look for a candidate is the one at the top of the bounds
672     *                           if topFocus is true, or at the bottom of the bounds if topFocus is
673     *                           false
674     * @param top                the top offset of the bounds in which a focusable must be
675     *                           found (the fading edge is assumed to start at this position)
676     * @param preferredFocusable the View that has highest priority and will be
677     *                           returned if it is within my bounds (null is valid)
678     * @return the next focusable component in the bounds or null if none can be
679     *         found
680     */
681    private View findFocusableViewInMyBounds(final boolean topFocus,
682            final int top, View preferredFocusable) {
683        /*
684         * The fading edge's transparent side should be considered for focus
685         * since it's mostly visible, so we divide the actual fading edge length
686         * by 2.
687         */
688        final int fadingEdgeLength = getVerticalFadingEdgeLength() / 2;
689        final int topWithoutFadingEdge = top + fadingEdgeLength;
690        final int bottomWithoutFadingEdge = top + getHeight() - fadingEdgeLength;
691
692        if ((preferredFocusable != null)
693                && (preferredFocusable.getTop() < bottomWithoutFadingEdge)
694                && (preferredFocusable.getBottom() > topWithoutFadingEdge)) {
695            return preferredFocusable;
696        }
697
698        return findFocusableViewInBounds(topFocus, topWithoutFadingEdge,
699                bottomWithoutFadingEdge);
700    }
701
702    /**
703     * <p>
704     * Finds the next focusable component that fits in the specified bounds.
705     * </p>
706     *
707     * @param topFocus look for a candidate is the one at the top of the bounds
708     *                 if topFocus is true, or at the bottom of the bounds if topFocus is
709     *                 false
710     * @param top      the top offset of the bounds in which a focusable must be
711     *                 found
712     * @param bottom   the bottom offset of the bounds in which a focusable must
713     *                 be found
714     * @return the next focusable component in the bounds or null if none can
715     *         be found
716     */
717    private View findFocusableViewInBounds(boolean topFocus, int top, int bottom) {
718
719        List<View> focusables = getFocusables(View.FOCUS_FORWARD);
720        View focusCandidate = null;
721
722        /*
723         * A fully contained focusable is one where its top is below the bound's
724         * top, and its bottom is above the bound's bottom. A partially
725         * contained focusable is one where some part of it is within the
726         * bounds, but it also has some part that is not within bounds.  A fully contained
727         * focusable is preferred to a partially contained focusable.
728         */
729        boolean foundFullyContainedFocusable = false;
730
731        int count = focusables.size();
732        for (int i = 0; i < count; i++) {
733            View view = focusables.get(i);
734            int viewTop = view.getTop();
735            int viewBottom = view.getBottom();
736
737            if (top < viewBottom && viewTop < bottom) {
738                /*
739                 * the focusable is in the target area, it is a candidate for
740                 * focusing
741                 */
742
743                final boolean viewIsFullyContained = (top < viewTop) &&
744                        (viewBottom < bottom);
745
746                if (focusCandidate == null) {
747                    /* No candidate, take this one */
748                    focusCandidate = view;
749                    foundFullyContainedFocusable = viewIsFullyContained;
750                } else {
751                    final boolean viewIsCloserToBoundary =
752                            (topFocus && viewTop < focusCandidate.getTop()) ||
753                                    (!topFocus && viewBottom > focusCandidate
754                                            .getBottom());
755
756                    if (foundFullyContainedFocusable) {
757                        if (viewIsFullyContained && viewIsCloserToBoundary) {
758                            /*
759                             * We're dealing with only fully contained views, so
760                             * it has to be closer to the boundary to beat our
761                             * candidate
762                             */
763                            focusCandidate = view;
764                        }
765                    } else {
766                        if (viewIsFullyContained) {
767                            /* Any fully contained view beats a partially contained view */
768                            focusCandidate = view;
769                            foundFullyContainedFocusable = true;
770                        } else if (viewIsCloserToBoundary) {
771                            /*
772                             * Partially contained view beats another partially
773                             * contained view if it's closer
774                             */
775                            focusCandidate = view;
776                        }
777                    }
778                }
779            }
780        }
781
782        return focusCandidate;
783    }
784
785    /**
786     * <p>Handles scrolling in response to a "page up/down" shortcut press. This
787     * method will scroll the view by one page up or down and give the focus
788     * to the topmost/bottommost component in the new visible area. If no
789     * component is a good candidate for focus, this scrollview reclaims the
790     * focus.</p>
791     *
792     * @param direction the scroll direction: {@link android.view.View#FOCUS_UP}
793     *                  to go one page up or
794     *                  {@link android.view.View#FOCUS_DOWN} to go one page down
795     * @return true if the key event is consumed by this method, false otherwise
796     */
797    public boolean pageScroll(int direction) {
798        boolean down = direction == View.FOCUS_DOWN;
799        int height = getHeight();
800
801        if (down) {
802            mTempRect.top = getScrollY() + height;
803            int count = getChildCount();
804            if (count > 0) {
805                View view = getChildAt(count - 1);
806                if (mTempRect.top + height > view.getBottom()) {
807                    mTempRect.top = view.getBottom() - height;
808                }
809            }
810        } else {
811            mTempRect.top = getScrollY() - height;
812            if (mTempRect.top < 0) {
813                mTempRect.top = 0;
814            }
815        }
816        mTempRect.bottom = mTempRect.top + height;
817
818        return scrollAndFocus(direction, mTempRect.top, mTempRect.bottom);
819    }
820
821    /**
822     * <p>Handles scrolling in response to a "home/end" shortcut press. This
823     * method will scroll the view to the top or bottom and give the focus
824     * to the topmost/bottommost component in the new visible area. If no
825     * component is a good candidate for focus, this scrollview reclaims the
826     * focus.</p>
827     *
828     * @param direction the scroll direction: {@link android.view.View#FOCUS_UP}
829     *                  to go the top of the view or
830     *                  {@link android.view.View#FOCUS_DOWN} to go the bottom
831     * @return true if the key event is consumed by this method, false otherwise
832     */
833    public boolean fullScroll(int direction) {
834        boolean down = direction == View.FOCUS_DOWN;
835        int height = getHeight();
836
837        mTempRect.top = 0;
838        mTempRect.bottom = height;
839
840        if (down) {
841            int count = getChildCount();
842            if (count > 0) {
843                View view = getChildAt(count - 1);
844                mTempRect.bottom = view.getBottom();
845                mTempRect.top = mTempRect.bottom - height;
846            }
847        }
848
849        return scrollAndFocus(direction, mTempRect.top, mTempRect.bottom);
850    }
851
852    /**
853     * <p>Scrolls the view to make the area defined by <code>top</code> and
854     * <code>bottom</code> visible. This method attempts to give the focus
855     * to a component visible in this area. If no component can be focused in
856     * the new visible area, the focus is reclaimed by this scrollview.</p>
857     *
858     * @param direction the scroll direction: {@link android.view.View#FOCUS_UP}
859     *                  to go upward
860     *                  {@link android.view.View#FOCUS_DOWN} to downward
861     * @param top       the top offset of the new area to be made visible
862     * @param bottom    the bottom offset of the new area to be made visible
863     * @return true if the key event is consumed by this method, false otherwise
864     */
865    private boolean scrollAndFocus(int direction, int top, int bottom) {
866        boolean handled = true;
867
868        int height = getHeight();
869        int containerTop = getScrollY();
870        int containerBottom = containerTop + height;
871        boolean up = direction == View.FOCUS_UP;
872
873        View newFocused = findFocusableViewInBounds(up, top, bottom);
874        if (newFocused == null) {
875            newFocused = this;
876        }
877
878        if (top >= containerTop && bottom <= containerBottom) {
879            handled = false;
880        } else {
881            int delta = up ? (top - containerTop) : (bottom - containerBottom);
882            doScrollY(delta);
883        }
884
885        if (newFocused != findFocus() && newFocused.requestFocus(direction)) {
886            mScrollViewMovedFocus = true;
887            mScrollViewMovedFocus = false;
888        }
889
890        return handled;
891    }
892
893    /**
894     * Handle scrolling in response to an up or down arrow click.
895     *
896     * @param direction The direction corresponding to the arrow key that was
897     *                  pressed
898     * @return True if we consumed the event, false otherwise
899     */
900    public boolean arrowScroll(int direction) {
901
902        View currentFocused = findFocus();
903        if (currentFocused == this) currentFocused = null;
904
905        View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, direction);
906
907        final int maxJump = getMaxScrollAmount();
908
909        if (nextFocused != null && isWithinDeltaOfScreen(nextFocused, maxJump, getHeight())) {
910            nextFocused.getDrawingRect(mTempRect);
911            offsetDescendantRectToMyCoords(nextFocused, mTempRect);
912            int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
913            doScrollY(scrollDelta);
914            nextFocused.requestFocus(direction);
915        } else {
916            // no new focus
917            int scrollDelta = maxJump;
918
919            if (direction == View.FOCUS_UP && getScrollY() < scrollDelta) {
920                scrollDelta = getScrollY();
921            } else if (direction == View.FOCUS_DOWN) {
922                if (getChildCount() > 0) {
923                    int daBottom = getChildAt(0).getBottom();
924
925                    int screenBottom = getScrollY() + getHeight();
926
927                    if (daBottom - screenBottom < maxJump) {
928                        scrollDelta = daBottom - screenBottom;
929                    }
930                }
931            }
932            if (scrollDelta == 0) {
933                return false;
934            }
935            doScrollY(direction == View.FOCUS_DOWN ? scrollDelta : -scrollDelta);
936        }
937
938        if (currentFocused != null && currentFocused.isFocused()
939                && isOffScreen(currentFocused)) {
940            // previously focused item still has focus and is off screen, give
941            // it up (take it back to ourselves)
942            // (also, need to temporarily force FOCUS_BEFORE_DESCENDANTS so we are
943            // sure to
944            // get it)
945            final int descendantFocusability = getDescendantFocusability();  // save
946            setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
947            requestFocus();
948            setDescendantFocusability(descendantFocusability);  // restore
949        }
950        return true;
951    }
952
953    /**
954     * @return whether the descendant of this scroll view is scrolled off
955     *  screen.
956     */
957    private boolean isOffScreen(View descendant) {
958        return !isWithinDeltaOfScreen(descendant, 0, getHeight());
959    }
960
961    /**
962     * @return whether the descendant of this scroll view is within delta
963     *  pixels of being on the screen.
964     */
965    private boolean isWithinDeltaOfScreen(View descendant, int delta, int height) {
966        descendant.getDrawingRect(mTempRect);
967        offsetDescendantRectToMyCoords(descendant, mTempRect);
968
969        return (mTempRect.bottom + delta) >= getScrollY()
970                && (mTempRect.top - delta) <= (getScrollY() + height);
971    }
972
973    /**
974     * Smooth scroll by a Y delta
975     *
976     * @param delta the number of pixels to scroll by on the Y axis
977     */
978    private void doScrollY(int delta) {
979        if (delta != 0) {
980            if (mSmoothScrollingEnabled) {
981                smoothScrollBy(0, delta);
982            } else {
983                scrollBy(0, delta);
984            }
985        }
986    }
987
988    /**
989     * Like {@link View#scrollBy}, but scroll smoothly instead of immediately.
990     *
991     * @param dx the number of pixels to scroll by on the X axis
992     * @param dy the number of pixels to scroll by on the Y axis
993     */
994    public final void smoothScrollBy(int dx, int dy) {
995        if (getChildCount() == 0) {
996            // Nothing to do.
997            return;
998        }
999        long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll;
1000        if (duration > ANIMATED_SCROLL_GAP) {
1001            final int height = getHeight() - mPaddingBottom - mPaddingTop;
1002            final int bottom = getChildAt(0).getHeight();
1003            final int maxY = Math.max(0, bottom - height);
1004            final int scrollY = mScrollY;
1005            dy = Math.max(0, Math.min(scrollY + dy, maxY)) - scrollY;
1006
1007            mScroller.startScroll(mScrollX, scrollY, 0, dy);
1008            invalidate();
1009        } else {
1010            if (!mScroller.isFinished()) {
1011                mScroller.abortAnimation();
1012                if (mFlingStrictSpan != null) {
1013                    mFlingStrictSpan.finish();
1014                    mFlingStrictSpan = null;
1015                }
1016            }
1017            scrollBy(dx, dy);
1018        }
1019        mLastScroll = AnimationUtils.currentAnimationTimeMillis();
1020    }
1021
1022    /**
1023     * Like {@link #scrollTo}, but scroll smoothly instead of immediately.
1024     *
1025     * @param x the position where to scroll on the X axis
1026     * @param y the position where to scroll on the Y axis
1027     */
1028    public final void smoothScrollTo(int x, int y) {
1029        smoothScrollBy(x - mScrollX, y - mScrollY);
1030    }
1031
1032    /**
1033     * <p>The scroll range of a scroll view is the overall height of all of its
1034     * children.</p>
1035     */
1036    @Override
1037    protected int computeVerticalScrollRange() {
1038        final int count = getChildCount();
1039        final int contentHeight = getHeight() - mPaddingBottom - mPaddingTop;
1040        if (count == 0) {
1041            return contentHeight;
1042        }
1043
1044        int scrollRange = getChildAt(0).getBottom();
1045        final int scrollY = mScrollY;
1046        final int overscrollBottom = Math.max(0, scrollRange - contentHeight);
1047        if (scrollY < 0) {
1048            scrollRange -= scrollY;
1049        } else if (scrollY > overscrollBottom) {
1050            scrollRange += scrollY - overscrollBottom;
1051        }
1052
1053        return scrollRange;
1054    }
1055
1056    @Override
1057    protected int computeVerticalScrollOffset() {
1058        return Math.max(0, super.computeVerticalScrollOffset());
1059    }
1060
1061    @Override
1062    protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) {
1063        ViewGroup.LayoutParams lp = child.getLayoutParams();
1064
1065        int childWidthMeasureSpec;
1066        int childHeightMeasureSpec;
1067
1068        childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, mPaddingLeft
1069                + mPaddingRight, lp.width);
1070
1071        childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
1072
1073        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1074    }
1075
1076    @Override
1077    protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed,
1078            int parentHeightMeasureSpec, int heightUsed) {
1079        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
1080
1081        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
1082                mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
1083                        + widthUsed, lp.width);
1084        final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
1085                lp.topMargin + lp.bottomMargin, MeasureSpec.UNSPECIFIED);
1086
1087        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1088    }
1089
1090    @Override
1091    public void computeScroll() {
1092        if (mScroller.computeScrollOffset()) {
1093            // This is called at drawing time by ViewGroup.  We don't want to
1094            // re-show the scrollbars at this point, which scrollTo will do,
1095            // so we replicate most of scrollTo here.
1096            //
1097            //         It's a little odd to call onScrollChanged from inside the drawing.
1098            //
1099            //         It is, except when you remember that computeScroll() is used to
1100            //         animate scrolling. So unless we want to defer the onScrollChanged()
1101            //         until the end of the animated scrolling, we don't really have a
1102            //         choice here.
1103            //
1104            //         I agree.  The alternative, which I think would be worse, is to post
1105            //         something and tell the subclasses later.  This is bad because there
1106            //         will be a window where mScrollX/Y is different from what the app
1107            //         thinks it is.
1108            //
1109            int oldX = mScrollX;
1110            int oldY = mScrollY;
1111            int x = mScroller.getCurrX();
1112            int y = mScroller.getCurrY();
1113
1114            if (oldX != x || oldY != y) {
1115                overScrollBy(x - oldX, y - oldY, oldX, oldY, 0, getScrollRange(),
1116                        0, mOverflingDistance, false);
1117                onScrollChanged(mScrollX, mScrollY, oldX, oldY);
1118
1119                final int range = getScrollRange();
1120                final int overscrollMode = getOverScrollMode();
1121                if (overscrollMode == OVER_SCROLL_ALWAYS ||
1122                        (overscrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && range > 0)) {
1123                    if (y < 0 && oldY >= 0) {
1124                        mEdgeGlowTop.onAbsorb((int) mScroller.getCurrVelocity());
1125                    } else if (y > range && oldY <= range) {
1126                        mEdgeGlowBottom.onAbsorb((int) mScroller.getCurrVelocity());
1127                    }
1128                }
1129            }
1130            awakenScrollBars();
1131
1132            // Keep on drawing until the animation has finished.
1133            postInvalidate();
1134        } else {
1135            if (mFlingStrictSpan != null) {
1136                mFlingStrictSpan.finish();
1137                mFlingStrictSpan = null;
1138            }
1139        }
1140    }
1141
1142    /**
1143     * Scrolls the view to the given child.
1144     *
1145     * @param child the View to scroll to
1146     */
1147    private void scrollToChild(View child) {
1148        child.getDrawingRect(mTempRect);
1149
1150        /* Offset from child's local coordinates to ScrollView coordinates */
1151        offsetDescendantRectToMyCoords(child, mTempRect);
1152
1153        int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
1154
1155        if (scrollDelta != 0) {
1156            scrollBy(0, scrollDelta);
1157        }
1158    }
1159
1160    /**
1161     * If rect is off screen, scroll just enough to get it (or at least the
1162     * first screen size chunk of it) on screen.
1163     *
1164     * @param rect      The rectangle.
1165     * @param immediate True to scroll immediately without animation
1166     * @return true if scrolling was performed
1167     */
1168    private boolean scrollToChildRect(Rect rect, boolean immediate) {
1169        final int delta = computeScrollDeltaToGetChildRectOnScreen(rect);
1170        final boolean scroll = delta != 0;
1171        if (scroll) {
1172            if (immediate) {
1173                scrollBy(0, delta);
1174            } else {
1175                smoothScrollBy(0, delta);
1176            }
1177        }
1178        return scroll;
1179    }
1180
1181    /**
1182     * Compute the amount to scroll in the Y direction in order to get
1183     * a rectangle completely on the screen (or, if taller than the screen,
1184     * at least the first screen size chunk of it).
1185     *
1186     * @param rect The rect.
1187     * @return The scroll delta.
1188     */
1189    protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) {
1190        if (getChildCount() == 0) return 0;
1191
1192        int height = getHeight();
1193        int screenTop = getScrollY();
1194        int screenBottom = screenTop + height;
1195
1196        int fadingEdge = getVerticalFadingEdgeLength();
1197
1198        // leave room for top fading edge as long as rect isn't at very top
1199        if (rect.top > 0) {
1200            screenTop += fadingEdge;
1201        }
1202
1203        // leave room for bottom fading edge as long as rect isn't at very bottom
1204        if (rect.bottom < getChildAt(0).getHeight()) {
1205            screenBottom -= fadingEdge;
1206        }
1207
1208        int scrollYDelta = 0;
1209
1210        if (rect.bottom > screenBottom && rect.top > screenTop) {
1211            // need to move down to get it in view: move down just enough so
1212            // that the entire rectangle is in view (or at least the first
1213            // screen size chunk).
1214
1215            if (rect.height() > height) {
1216                // just enough to get screen size chunk on
1217                scrollYDelta += (rect.top - screenTop);
1218            } else {
1219                // get entire rect at bottom of screen
1220                scrollYDelta += (rect.bottom - screenBottom);
1221            }
1222
1223            // make sure we aren't scrolling beyond the end of our content
1224            int bottom = getChildAt(0).getBottom();
1225            int distanceToBottom = bottom - screenBottom;
1226            scrollYDelta = Math.min(scrollYDelta, distanceToBottom);
1227
1228        } else if (rect.top < screenTop && rect.bottom < screenBottom) {
1229            // need to move up to get it in view: move up just enough so that
1230            // entire rectangle is in view (or at least the first screen
1231            // size chunk of it).
1232
1233            if (rect.height() > height) {
1234                // screen size chunk
1235                scrollYDelta -= (screenBottom - rect.bottom);
1236            } else {
1237                // entire rect at top
1238                scrollYDelta -= (screenTop - rect.top);
1239            }
1240
1241            // make sure we aren't scrolling any further than the top our content
1242            scrollYDelta = Math.max(scrollYDelta, -getScrollY());
1243        }
1244        return scrollYDelta;
1245    }
1246
1247    @Override
1248    public void requestChildFocus(View child, View focused) {
1249        if (!mScrollViewMovedFocus) {
1250            if (!mIsLayoutDirty) {
1251                scrollToChild(focused);
1252            } else {
1253                // The child may not be laid out yet, we can't compute the scroll yet
1254                mChildToScrollTo = focused;
1255            }
1256        }
1257        super.requestChildFocus(child, focused);
1258    }
1259
1260
1261    /**
1262     * When looking for focus in children of a scroll view, need to be a little
1263     * more careful not to give focus to something that is scrolled off screen.
1264     *
1265     * This is more expensive than the default {@link android.view.ViewGroup}
1266     * implementation, otherwise this behavior might have been made the default.
1267     */
1268    @Override
1269    protected boolean onRequestFocusInDescendants(int direction,
1270            Rect previouslyFocusedRect) {
1271
1272        // convert from forward / backward notation to up / down / left / right
1273        // (ugh).
1274        if (direction == View.FOCUS_FORWARD) {
1275            direction = View.FOCUS_DOWN;
1276        } else if (direction == View.FOCUS_BACKWARD) {
1277            direction = View.FOCUS_UP;
1278        }
1279
1280        final View nextFocus = previouslyFocusedRect == null ?
1281                FocusFinder.getInstance().findNextFocus(this, null, direction) :
1282                FocusFinder.getInstance().findNextFocusFromRect(this,
1283                        previouslyFocusedRect, direction);
1284
1285        if (nextFocus == null) {
1286            return false;
1287        }
1288
1289        if (isOffScreen(nextFocus)) {
1290            return false;
1291        }
1292
1293        return nextFocus.requestFocus(direction, previouslyFocusedRect);
1294    }
1295
1296    @Override
1297    public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
1298            boolean immediate) {
1299        // offset into coordinate space of this scroll view
1300        rectangle.offset(child.getLeft() - child.getScrollX(),
1301                child.getTop() - child.getScrollY());
1302
1303        return scrollToChildRect(rectangle, immediate);
1304    }
1305
1306    @Override
1307    public void requestLayout() {
1308        mIsLayoutDirty = true;
1309        super.requestLayout();
1310    }
1311
1312    @Override
1313    protected void onDetachedFromWindow() {
1314        super.onDetachedFromWindow();
1315
1316        if (mScrollStrictSpan != null) {
1317            mScrollStrictSpan.finish();
1318            mScrollStrictSpan = null;
1319        }
1320        if (mFlingStrictSpan != null) {
1321            mFlingStrictSpan.finish();
1322            mFlingStrictSpan = null;
1323        }
1324    }
1325
1326    @Override
1327    protected void onLayout(boolean changed, int l, int t, int r, int b) {
1328        super.onLayout(changed, l, t, r, b);
1329        mIsLayoutDirty = false;
1330        // Give a child focus if it needs it
1331        if (mChildToScrollTo != null && isViewDescendantOf(mChildToScrollTo, this)) {
1332            scrollToChild(mChildToScrollTo);
1333        }
1334        mChildToScrollTo = null;
1335
1336        // Calling this with the present values causes it to re-clam them
1337        scrollTo(mScrollX, mScrollY);
1338    }
1339
1340    @Override
1341    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
1342        super.onSizeChanged(w, h, oldw, oldh);
1343
1344        View currentFocused = findFocus();
1345        if (null == currentFocused || this == currentFocused)
1346            return;
1347
1348        // If the currently-focused view was visible on the screen when the
1349        // screen was at the old height, then scroll the screen to make that
1350        // view visible with the new screen height.
1351        if (isWithinDeltaOfScreen(currentFocused, 0, oldh)) {
1352            currentFocused.getDrawingRect(mTempRect);
1353            offsetDescendantRectToMyCoords(currentFocused, mTempRect);
1354            int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
1355            doScrollY(scrollDelta);
1356        }
1357    }
1358
1359    /**
1360     * Return true if child is an descendant of parent, (or equal to the parent).
1361     */
1362    private boolean isViewDescendantOf(View child, View parent) {
1363        if (child == parent) {
1364            return true;
1365        }
1366
1367        final ViewParent theParent = child.getParent();
1368        return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1369    }
1370
1371    /**
1372     * Fling the scroll view
1373     *
1374     * @param velocityY The initial velocity in the Y direction. Positive
1375     *                  numbers mean that the finger/cursor is moving down the screen,
1376     *                  which means we want to scroll towards the top.
1377     */
1378    public void fling(int velocityY) {
1379        if (getChildCount() > 0) {
1380            int height = getHeight() - mPaddingBottom - mPaddingTop;
1381            int bottom = getChildAt(0).getHeight();
1382
1383            mScroller.fling(mScrollX, mScrollY, 0, velocityY, 0, 0, 0,
1384                    Math.max(0, bottom - height), 0, height/2);
1385
1386            final boolean movingDown = velocityY > 0;
1387
1388            View newFocused =
1389                    findFocusableViewInMyBounds(movingDown, mScroller.getFinalY(), findFocus());
1390            if (newFocused == null) {
1391                newFocused = this;
1392            }
1393
1394            if (newFocused != findFocus()
1395                    && newFocused.requestFocus(movingDown ? View.FOCUS_DOWN : View.FOCUS_UP)) {
1396                mScrollViewMovedFocus = true;
1397                mScrollViewMovedFocus = false;
1398            }
1399
1400            if (mFlingStrictSpan == null) {
1401                mFlingStrictSpan = StrictMode.enterCriticalSpan("ScrollView-fling");
1402            }
1403
1404            invalidate();
1405        }
1406    }
1407
1408    private void endDrag() {
1409        mIsBeingDragged = false;
1410
1411        if (mVelocityTracker != null) {
1412            mVelocityTracker.recycle();
1413            mVelocityTracker = null;
1414        }
1415
1416        if (mEdgeGlowTop != null) {
1417            mEdgeGlowTop.onRelease();
1418            mEdgeGlowBottom.onRelease();
1419        }
1420
1421        if (mScrollStrictSpan != null) {
1422            mScrollStrictSpan.finish();
1423            mScrollStrictSpan = null;
1424        }
1425    }
1426
1427    /**
1428     * {@inheritDoc}
1429     *
1430     * <p>This version also clamps the scrolling to the bounds of our child.
1431     */
1432    @Override
1433    public void scrollTo(int x, int y) {
1434        // we rely on the fact the View.scrollBy calls scrollTo.
1435        if (getChildCount() > 0) {
1436            View child = getChildAt(0);
1437            x = clamp(x, getWidth() - mPaddingRight - mPaddingLeft, child.getWidth());
1438            y = clamp(y, getHeight() - mPaddingBottom - mPaddingTop, child.getHeight());
1439            if (x != mScrollX || y != mScrollY) {
1440                super.scrollTo(x, y);
1441            }
1442        }
1443    }
1444
1445    @Override
1446    public void setOverScrollMode(int mode) {
1447        if (mode != OVER_SCROLL_NEVER) {
1448            if (mEdgeGlowTop == null) {
1449                Context context = getContext();
1450                final Resources res = context.getResources();
1451                final Drawable edge = res.getDrawable(R.drawable.overscroll_edge);
1452                final Drawable glow = res.getDrawable(R.drawable.overscroll_glow);
1453                mEdgeGlowTop = new EdgeGlow(context, edge, glow);
1454                mEdgeGlowBottom = new EdgeGlow(context, edge, glow);
1455            }
1456        } else {
1457            mEdgeGlowTop = null;
1458            mEdgeGlowBottom = null;
1459        }
1460        super.setOverScrollMode(mode);
1461    }
1462
1463    @Override
1464    public void draw(Canvas canvas) {
1465        super.draw(canvas);
1466        if (mEdgeGlowTop != null) {
1467            final int scrollY = mScrollY;
1468            if (!mEdgeGlowTop.isFinished()) {
1469                final int restoreCount = canvas.save();
1470                final int width = getWidth();
1471
1472                canvas.translate(0, Math.min(0, scrollY));
1473                mEdgeGlowTop.setSize(width, getHeight());
1474                if (mEdgeGlowTop.draw(canvas)) {
1475                    invalidate();
1476                }
1477                canvas.restoreToCount(restoreCount);
1478            }
1479            if (!mEdgeGlowBottom.isFinished()) {
1480                final int restoreCount = canvas.save();
1481                final int width = getWidth();
1482                final int height = getHeight();
1483
1484                canvas.translate(-width, Math.max(getScrollRange(), scrollY) + height);
1485                canvas.rotate(180, width, 0);
1486                mEdgeGlowBottom.setSize(width, height);
1487                if (mEdgeGlowBottom.draw(canvas)) {
1488                    invalidate();
1489                }
1490                canvas.restoreToCount(restoreCount);
1491            }
1492        }
1493    }
1494
1495    private int clamp(int n, int my, int child) {
1496        if (my >= child || n < 0) {
1497            /* my >= child is this case:
1498             *                    |--------------- me ---------------|
1499             *     |------ child ------|
1500             * or
1501             *     |--------------- me ---------------|
1502             *            |------ child ------|
1503             * or
1504             *     |--------------- me ---------------|
1505             *                                  |------ child ------|
1506             *
1507             * n < 0 is this case:
1508             *     |------ me ------|
1509             *                    |-------- child --------|
1510             *     |-- mScrollX --|
1511             */
1512            return 0;
1513        }
1514        if ((my+n) > child) {
1515            /* this case:
1516             *                    |------ me ------|
1517             *     |------ child ------|
1518             *     |-- mScrollX --|
1519             */
1520            return child-my;
1521        }
1522        return n;
1523    }
1524}
1525