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