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