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