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