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