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