ScrollView.java revision 0b8bb4282a7d1afb24f8c4d5beb2ca4ecc731116
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        int count = getChildCount();
896        if (count == 0) {
897            return getHeight();
898        }
899
900        int scrollRange = getChildAt(0).getBottom();
901        int scrollY = mScrollY;
902        int overscrollBottom = scrollRange - getHeight() - mPaddingBottom - mPaddingTop;
903        if (scrollY < 0) {
904            scrollRange -= scrollY;
905        } else if (scrollY > overscrollBottom) {
906            scrollRange += scrollY - overscrollBottom;
907        }
908
909        return scrollRange;
910    }
911
912    @Override
913    protected int computeVerticalScrollOffset() {
914        return Math.max(0, super.computeVerticalScrollOffset());
915    }
916
917    @Override
918    protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) {
919        ViewGroup.LayoutParams lp = child.getLayoutParams();
920
921        int childWidthMeasureSpec;
922        int childHeightMeasureSpec;
923
924        childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, mPaddingLeft
925                + mPaddingRight, lp.width);
926
927        childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
928
929        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
930    }
931
932    @Override
933    protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed,
934            int parentHeightMeasureSpec, int heightUsed) {
935        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
936
937        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
938                mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
939                        + widthUsed, lp.width);
940        final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
941                lp.topMargin + lp.bottomMargin, MeasureSpec.UNSPECIFIED);
942
943        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
944    }
945
946    @Override
947    public void computeScroll() {
948        if (mScroller.computeScrollOffset()) {
949            // This is called at drawing time by ViewGroup.  We don't want to
950            // re-show the scrollbars at this point, which scrollTo will do,
951            // so we replicate most of scrollTo here.
952            //
953            //         It's a little odd to call onScrollChanged from inside the drawing.
954            //
955            //         It is, except when you remember that computeScroll() is used to
956            //         animate scrolling. So unless we want to defer the onScrollChanged()
957            //         until the end of the animated scrolling, we don't really have a
958            //         choice here.
959            //
960            //         I agree.  The alternative, which I think would be worse, is to post
961            //         something and tell the subclasses later.  This is bad because there
962            //         will be a window where mScrollX/Y is different from what the app
963            //         thinks it is.
964            //
965            int oldX = mScrollX;
966            int oldY = mScrollY;
967            int x = mScroller.getCurrX();
968            int y = mScroller.getCurrY();
969
970            if (oldX != x || oldY != y) {
971                overscrollBy(x - oldX, y - oldY, oldX, oldY, 0, getScrollRange(),
972                        0, getOverscrollMax());
973                onScrollChanged(mScrollX, mScrollY, oldX, oldY);
974            }
975
976            // Keep on drawing until the animation has finished.
977            postInvalidate();
978        }
979    }
980
981    /**
982     * Scrolls the view to the given child.
983     *
984     * @param child the View to scroll to
985     */
986    private void scrollToChild(View child) {
987        child.getDrawingRect(mTempRect);
988
989        /* Offset from child's local coordinates to ScrollView coordinates */
990        offsetDescendantRectToMyCoords(child, mTempRect);
991
992        int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
993
994        if (scrollDelta != 0) {
995            scrollBy(0, scrollDelta);
996        }
997    }
998
999    /**
1000     * If rect is off screen, scroll just enough to get it (or at least the
1001     * first screen size chunk of it) on screen.
1002     *
1003     * @param rect      The rectangle.
1004     * @param immediate True to scroll immediately without animation
1005     * @return true if scrolling was performed
1006     */
1007    private boolean scrollToChildRect(Rect rect, boolean immediate) {
1008        final int delta = computeScrollDeltaToGetChildRectOnScreen(rect);
1009        final boolean scroll = delta != 0;
1010        if (scroll) {
1011            if (immediate) {
1012                scrollBy(0, delta);
1013            } else {
1014                smoothScrollBy(0, delta);
1015            }
1016        }
1017        return scroll;
1018    }
1019
1020    /**
1021     * Compute the amount to scroll in the Y direction in order to get
1022     * a rectangle completely on the screen (or, if taller than the screen,
1023     * at least the first screen size chunk of it).
1024     *
1025     * @param rect The rect.
1026     * @return The scroll delta.
1027     */
1028    protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) {
1029        if (getChildCount() == 0) return 0;
1030
1031        int height = getHeight();
1032        int screenTop = getScrollY();
1033        int screenBottom = screenTop + height;
1034
1035        int fadingEdge = getVerticalFadingEdgeLength();
1036
1037        // leave room for top fading edge as long as rect isn't at very top
1038        if (rect.top > 0) {
1039            screenTop += fadingEdge;
1040        }
1041
1042        // leave room for bottom fading edge as long as rect isn't at very bottom
1043        if (rect.bottom < getChildAt(0).getHeight()) {
1044            screenBottom -= fadingEdge;
1045        }
1046
1047        int scrollYDelta = 0;
1048
1049        if (rect.bottom > screenBottom && rect.top > screenTop) {
1050            // need to move down to get it in view: move down just enough so
1051            // that the entire rectangle is in view (or at least the first
1052            // screen size chunk).
1053
1054            if (rect.height() > height) {
1055                // just enough to get screen size chunk on
1056                scrollYDelta += (rect.top - screenTop);
1057            } else {
1058                // get entire rect at bottom of screen
1059                scrollYDelta += (rect.bottom - screenBottom);
1060            }
1061
1062            // make sure we aren't scrolling beyond the end of our content
1063            int bottom = getChildAt(0).getBottom();
1064            int distanceToBottom = bottom - screenBottom;
1065            scrollYDelta = Math.min(scrollYDelta, distanceToBottom);
1066
1067        } else if (rect.top < screenTop && rect.bottom < screenBottom) {
1068            // need to move up to get it in view: move up just enough so that
1069            // entire rectangle is in view (or at least the first screen
1070            // size chunk of it).
1071
1072            if (rect.height() > height) {
1073                // screen size chunk
1074                scrollYDelta -= (screenBottom - rect.bottom);
1075            } else {
1076                // entire rect at top
1077                scrollYDelta -= (screenTop - rect.top);
1078            }
1079
1080            // make sure we aren't scrolling any further than the top our content
1081            scrollYDelta = Math.max(scrollYDelta, -getScrollY());
1082        }
1083        return scrollYDelta;
1084    }
1085
1086    @Override
1087    public void requestChildFocus(View child, View focused) {
1088        if (!mScrollViewMovedFocus) {
1089            if (!mIsLayoutDirty) {
1090                scrollToChild(focused);
1091            } else {
1092                // The child may not be laid out yet, we can't compute the scroll yet
1093                mChildToScrollTo = focused;
1094            }
1095        }
1096        super.requestChildFocus(child, focused);
1097    }
1098
1099
1100    /**
1101     * When looking for focus in children of a scroll view, need to be a little
1102     * more careful not to give focus to something that is scrolled off screen.
1103     *
1104     * This is more expensive than the default {@link android.view.ViewGroup}
1105     * implementation, otherwise this behavior might have been made the default.
1106     */
1107    @Override
1108    protected boolean onRequestFocusInDescendants(int direction,
1109            Rect previouslyFocusedRect) {
1110
1111        // convert from forward / backward notation to up / down / left / right
1112        // (ugh).
1113        if (direction == View.FOCUS_FORWARD) {
1114            direction = View.FOCUS_DOWN;
1115        } else if (direction == View.FOCUS_BACKWARD) {
1116            direction = View.FOCUS_UP;
1117        }
1118
1119        final View nextFocus = previouslyFocusedRect == null ?
1120                FocusFinder.getInstance().findNextFocus(this, null, direction) :
1121                FocusFinder.getInstance().findNextFocusFromRect(this,
1122                        previouslyFocusedRect, direction);
1123
1124        if (nextFocus == null) {
1125            return false;
1126        }
1127
1128        if (isOffScreen(nextFocus)) {
1129            return false;
1130        }
1131
1132        return nextFocus.requestFocus(direction, previouslyFocusedRect);
1133    }
1134
1135    @Override
1136    public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
1137            boolean immediate) {
1138        // offset into coordinate space of this scroll view
1139        rectangle.offset(child.getLeft() - child.getScrollX(),
1140                child.getTop() - child.getScrollY());
1141
1142        return scrollToChildRect(rectangle, immediate);
1143    }
1144
1145    @Override
1146    public void requestLayout() {
1147        mIsLayoutDirty = true;
1148        super.requestLayout();
1149    }
1150
1151    @Override
1152    protected void onLayout(boolean changed, int l, int t, int r, int b) {
1153        super.onLayout(changed, l, t, r, b);
1154        mIsLayoutDirty = false;
1155        // Give a child focus if it needs it
1156        if (mChildToScrollTo != null && isViewDescendantOf(mChildToScrollTo, this)) {
1157                scrollToChild(mChildToScrollTo);
1158        }
1159        mChildToScrollTo = null;
1160
1161        // Calling this with the present values causes it to re-clam them
1162        scrollTo(mScrollX, mScrollY);
1163    }
1164
1165    @Override
1166    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
1167        super.onSizeChanged(w, h, oldw, oldh);
1168
1169        View currentFocused = findFocus();
1170        if (null == currentFocused || this == currentFocused)
1171            return;
1172
1173        // If the currently-focused view was visible on the screen when the
1174        // screen was at the old height, then scroll the screen to make that
1175        // view visible with the new screen height.
1176        if (isWithinDeltaOfScreen(currentFocused, 0, oldh)) {
1177            currentFocused.getDrawingRect(mTempRect);
1178            offsetDescendantRectToMyCoords(currentFocused, mTempRect);
1179            int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
1180            doScrollY(scrollDelta);
1181        }
1182    }
1183
1184    /**
1185     * Return true if child is an descendant of parent, (or equal to the parent).
1186     */
1187    private boolean isViewDescendantOf(View child, View parent) {
1188        if (child == parent) {
1189            return true;
1190        }
1191
1192        final ViewParent theParent = child.getParent();
1193        return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1194    }
1195
1196    /**
1197     * Fling the scroll view
1198     *
1199     * @param velocityY The initial velocity in the Y direction. Positive
1200     *                  numbers mean that the finger/curor is moving down the screen,
1201     *                  which means we want to scroll towards the top.
1202     */
1203    public void fling(int velocityY) {
1204        if (getChildCount() > 0) {
1205            int height = getHeight() - mPaddingBottom - mPaddingTop;
1206            int bottom = getChildAt(0).getHeight();
1207
1208            mScroller.fling(mScrollX, mScrollY, 0, velocityY, 0, 0, 0,
1209                    Math.max(0, bottom - height), 0, height/2);
1210
1211            final boolean movingDown = velocityY > 0;
1212
1213            View newFocused =
1214                    findFocusableViewInMyBounds(movingDown, mScroller.getFinalY(), findFocus());
1215            if (newFocused == null) {
1216                newFocused = this;
1217            }
1218
1219            if (newFocused != findFocus()
1220                    && newFocused.requestFocus(movingDown ? View.FOCUS_DOWN : View.FOCUS_UP)) {
1221                mScrollViewMovedFocus = true;
1222                mScrollViewMovedFocus = false;
1223            }
1224
1225            awakenScrollBars(mScroller.getDuration());
1226            invalidate();
1227        }
1228    }
1229
1230    /**
1231     * {@inheritDoc}
1232     *
1233     * <p>This version also clamps the scrolling to the bounds of our child.
1234     */
1235    public void scrollTo(int x, int y) {
1236        // we rely on the fact the View.scrollBy calls scrollTo.
1237        if (getChildCount() > 0) {
1238            View child = getChildAt(0);
1239            x = clamp(x, getWidth() - mPaddingRight - mPaddingLeft, child.getWidth());
1240            y = clamp(y, getHeight() - mPaddingBottom - mPaddingTop, child.getHeight());
1241            if (x != mScrollX || y != mScrollY) {
1242                super.scrollTo(x, y);
1243            }
1244        }
1245    }
1246
1247    private int clamp(int n, int my, int child) {
1248        if (my >= child || n < 0) {
1249            /* my >= child is this case:
1250             *                    |--------------- me ---------------|
1251             *     |------ child ------|
1252             * or
1253             *     |--------------- me ---------------|
1254             *            |------ child ------|
1255             * or
1256             *     |--------------- me ---------------|
1257             *                                  |------ child ------|
1258             *
1259             * n < 0 is this case:
1260             *     |------ me ------|
1261             *                    |-------- child --------|
1262             *     |-- mScrollX --|
1263             */
1264            return 0;
1265        }
1266        if ((my+n) > child) {
1267            /* this case:
1268             *                    |------ me ------|
1269             *     |------ child ------|
1270             *     |-- mScrollX --|
1271             */
1272            return child-my;
1273        }
1274        return n;
1275    }
1276}
1277