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