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