ScrollView.java revision f54460576e88d7531b171575d37264dfe0a34f33
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                super.scrollTo(mScrollX, mScrollY + deltaY);
463                break;
464            case MotionEvent.ACTION_UP:
465                final VelocityTracker velocityTracker = mVelocityTracker;
466                velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
467                int initialVelocity = (int) velocityTracker.getYVelocity();
468
469                if (getChildCount() > 0) {
470                    if ((Math.abs(initialVelocity) > mMinimumVelocity)) {
471                        fling(-initialVelocity);
472                    } else {
473                        final int bottom = Math.max(0, getChildAt(0).getHeight() -
474                                (getHeight() - mPaddingBottom - mPaddingTop));
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    /**
490     * <p>
491     * Finds the next focusable component that fits in this View's bounds
492     * (excluding fading edges) pretending that this View's top is located at
493     * the parameter top.
494     * </p>
495     *
496     * @param topFocus           look for a candidate is the one at the top of the bounds
497     *                           if topFocus is true, or at the bottom of the bounds if topFocus is
498     *                           false
499     * @param top                the top offset of the bounds in which a focusable must be
500     *                           found (the fading edge is assumed to start at this position)
501     * @param preferredFocusable the View that has highest priority and will be
502     *                           returned if it is within my bounds (null is valid)
503     * @return the next focusable component in the bounds or null if none can be
504     *         found
505     */
506    private View findFocusableViewInMyBounds(final boolean topFocus,
507            final int top, View preferredFocusable) {
508        /*
509         * The fading edge's transparent side should be considered for focus
510         * since it's mostly visible, so we divide the actual fading edge length
511         * by 2.
512         */
513        final int fadingEdgeLength = getVerticalFadingEdgeLength() / 2;
514        final int topWithoutFadingEdge = top + fadingEdgeLength;
515        final int bottomWithoutFadingEdge = top + getHeight() - fadingEdgeLength;
516
517        if ((preferredFocusable != null)
518                && (preferredFocusable.getTop() < bottomWithoutFadingEdge)
519                && (preferredFocusable.getBottom() > topWithoutFadingEdge)) {
520            return preferredFocusable;
521        }
522
523        return findFocusableViewInBounds(topFocus, topWithoutFadingEdge,
524                bottomWithoutFadingEdge);
525    }
526
527    /**
528     * <p>
529     * Finds the next focusable component that fits in the specified bounds.
530     * </p>
531     *
532     * @param topFocus look for a candidate is the one at the top of the bounds
533     *                 if topFocus is true, or at the bottom of the bounds if topFocus is
534     *                 false
535     * @param top      the top offset of the bounds in which a focusable must be
536     *                 found
537     * @param bottom   the bottom offset of the bounds in which a focusable must
538     *                 be found
539     * @return the next focusable component in the bounds or null if none can
540     *         be found
541     */
542    private View findFocusableViewInBounds(boolean topFocus, int top, int bottom) {
543
544        List<View> focusables = getFocusables(View.FOCUS_FORWARD);
545        View focusCandidate = null;
546
547        /*
548         * A fully contained focusable is one where its top is below the bound's
549         * top, and its bottom is above the bound's bottom. A partially
550         * contained focusable is one where some part of it is within the
551         * bounds, but it also has some part that is not within bounds.  A fully contained
552         * focusable is preferred to a partially contained focusable.
553         */
554        boolean foundFullyContainedFocusable = false;
555
556        int count = focusables.size();
557        for (int i = 0; i < count; i++) {
558            View view = focusables.get(i);
559            int viewTop = view.getTop();
560            int viewBottom = view.getBottom();
561
562            if (top < viewBottom && viewTop < bottom) {
563                /*
564                 * the focusable is in the target area, it is a candidate for
565                 * focusing
566                 */
567
568                final boolean viewIsFullyContained = (top < viewTop) &&
569                        (viewBottom < bottom);
570
571                if (focusCandidate == null) {
572                    /* No candidate, take this one */
573                    focusCandidate = view;
574                    foundFullyContainedFocusable = viewIsFullyContained;
575                } else {
576                    final boolean viewIsCloserToBoundary =
577                            (topFocus && viewTop < focusCandidate.getTop()) ||
578                                    (!topFocus && viewBottom > focusCandidate
579                                            .getBottom());
580
581                    if (foundFullyContainedFocusable) {
582                        if (viewIsFullyContained && viewIsCloserToBoundary) {
583                            /*
584                             * We're dealing with only fully contained views, so
585                             * it has to be closer to the boundary to beat our
586                             * candidate
587                             */
588                            focusCandidate = view;
589                        }
590                    } else {
591                        if (viewIsFullyContained) {
592                            /* Any fully contained view beats a partially contained view */
593                            focusCandidate = view;
594                            foundFullyContainedFocusable = true;
595                        } else if (viewIsCloserToBoundary) {
596                            /*
597                             * Partially contained view beats another partially
598                             * contained view if it's closer
599                             */
600                            focusCandidate = view;
601                        }
602                    }
603                }
604            }
605        }
606
607        return focusCandidate;
608    }
609
610    /**
611     * <p>Handles scrolling in response to a "page up/down" shortcut press. This
612     * method will scroll the view by one page up or down and give the focus
613     * to the topmost/bottommost component in the new visible area. If no
614     * component is a good candidate for focus, this scrollview reclaims the
615     * focus.</p>
616     *
617     * @param direction the scroll direction: {@link android.view.View#FOCUS_UP}
618     *                  to go one page up or
619     *                  {@link android.view.View#FOCUS_DOWN} to go one page down
620     * @return true if the key event is consumed by this method, false otherwise
621     */
622    public boolean pageScroll(int direction) {
623        boolean down = direction == View.FOCUS_DOWN;
624        int height = getHeight();
625
626        if (down) {
627            mTempRect.top = getScrollY() + height;
628            int count = getChildCount();
629            if (count > 0) {
630                View view = getChildAt(count - 1);
631                if (mTempRect.top + height > view.getBottom()) {
632                    mTempRect.top = view.getBottom() - height;
633                }
634            }
635        } else {
636            mTempRect.top = getScrollY() - height;
637            if (mTempRect.top < 0) {
638                mTempRect.top = 0;
639            }
640        }
641        mTempRect.bottom = mTempRect.top + height;
642
643        return scrollAndFocus(direction, mTempRect.top, mTempRect.bottom);
644    }
645
646    /**
647     * <p>Handles scrolling in response to a "home/end" shortcut press. This
648     * method will scroll the view to the top or bottom and give the focus
649     * to the topmost/bottommost component in the new visible area. If no
650     * component is a good candidate for focus, this scrollview reclaims the
651     * focus.</p>
652     *
653     * @param direction the scroll direction: {@link android.view.View#FOCUS_UP}
654     *                  to go the top of the view or
655     *                  {@link android.view.View#FOCUS_DOWN} to go the bottom
656     * @return true if the key event is consumed by this method, false otherwise
657     */
658    public boolean fullScroll(int direction) {
659        boolean down = direction == View.FOCUS_DOWN;
660        int height = getHeight();
661
662        mTempRect.top = 0;
663        mTempRect.bottom = height;
664
665        if (down) {
666            int count = getChildCount();
667            if (count > 0) {
668                View view = getChildAt(count - 1);
669                mTempRect.bottom = view.getBottom();
670                mTempRect.top = mTempRect.bottom - height;
671            }
672        }
673
674        return scrollAndFocus(direction, mTempRect.top, mTempRect.bottom);
675    }
676
677    /**
678     * <p>Scrolls the view to make the area defined by <code>top</code> and
679     * <code>bottom</code> visible. This method attempts to give the focus
680     * to a component visible in this area. If no component can be focused in
681     * the new visible area, the focus is reclaimed by this scrollview.</p>
682     *
683     * @param direction the scroll direction: {@link android.view.View#FOCUS_UP}
684     *                  to go upward
685     *                  {@link android.view.View#FOCUS_DOWN} to downward
686     * @param top       the top offset of the new area to be made visible
687     * @param bottom    the bottom offset of the new area to be made visible
688     * @return true if the key event is consumed by this method, false otherwise
689     */
690    private boolean scrollAndFocus(int direction, int top, int bottom) {
691        boolean handled = true;
692
693        int height = getHeight();
694        int containerTop = getScrollY();
695        int containerBottom = containerTop + height;
696        boolean up = direction == View.FOCUS_UP;
697
698        View newFocused = findFocusableViewInBounds(up, top, bottom);
699        if (newFocused == null) {
700            newFocused = this;
701        }
702
703        if (top >= containerTop && bottom <= containerBottom) {
704            handled = false;
705        } else {
706            int delta = up ? (top - containerTop) : (bottom - containerBottom);
707            doScrollY(delta);
708        }
709
710        if (newFocused != findFocus() && newFocused.requestFocus(direction)) {
711            mScrollViewMovedFocus = true;
712            mScrollViewMovedFocus = false;
713        }
714
715        return handled;
716    }
717
718    /**
719     * Handle scrolling in response to an up or down arrow click.
720     *
721     * @param direction The direction corresponding to the arrow key that was
722     *                  pressed
723     * @return True if we consumed the event, false otherwise
724     */
725    public boolean arrowScroll(int direction) {
726
727        View currentFocused = findFocus();
728        if (currentFocused == this) currentFocused = null;
729
730        View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, direction);
731
732        final int maxJump = getMaxScrollAmount();
733
734        if (nextFocused != null && isWithinDeltaOfScreen(nextFocused, maxJump, getHeight())) {
735            nextFocused.getDrawingRect(mTempRect);
736            offsetDescendantRectToMyCoords(nextFocused, mTempRect);
737            int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
738            doScrollY(scrollDelta);
739            nextFocused.requestFocus(direction);
740        } else {
741            // no new focus
742            int scrollDelta = maxJump;
743
744            if (direction == View.FOCUS_UP && getScrollY() < scrollDelta) {
745                scrollDelta = getScrollY();
746            } else if (direction == View.FOCUS_DOWN) {
747                if (getChildCount() > 0) {
748                    int daBottom = getChildAt(0).getBottom();
749
750                    int screenBottom = getScrollY() + getHeight();
751
752                    if (daBottom - screenBottom < maxJump) {
753                        scrollDelta = daBottom - screenBottom;
754                    }
755                }
756            }
757            if (scrollDelta == 0) {
758                return false;
759            }
760            doScrollY(direction == View.FOCUS_DOWN ? scrollDelta : -scrollDelta);
761        }
762
763        if (currentFocused != null && currentFocused.isFocused()
764                && isOffScreen(currentFocused)) {
765            // previously focused item still has focus and is off screen, give
766            // it up (take it back to ourselves)
767            // (also, need to temporarily force FOCUS_BEFORE_DESCENDANTS so we are
768            // sure to
769            // get it)
770            final int descendantFocusability = getDescendantFocusability();  // save
771            setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
772            requestFocus();
773            setDescendantFocusability(descendantFocusability);  // restore
774        }
775        return true;
776    }
777
778    /**
779     * @return whether the descendant of this scroll view is scrolled off
780     *  screen.
781     */
782    private boolean isOffScreen(View descendant) {
783        return !isWithinDeltaOfScreen(descendant, 0, getHeight());
784    }
785
786    /**
787     * @return whether the descendant of this scroll view is within delta
788     *  pixels of being on the screen.
789     */
790    private boolean isWithinDeltaOfScreen(View descendant, int delta, int height) {
791        descendant.getDrawingRect(mTempRect);
792        offsetDescendantRectToMyCoords(descendant, mTempRect);
793
794        return (mTempRect.bottom + delta) >= getScrollY()
795                && (mTempRect.top - delta) <= (getScrollY() + height);
796    }
797
798    /**
799     * Smooth scroll by a Y delta
800     *
801     * @param delta the number of pixels to scroll by on the Y axis
802     */
803    private void doScrollY(int delta) {
804        if (delta != 0) {
805            if (mSmoothScrollingEnabled) {
806                smoothScrollBy(0, delta);
807            } else {
808                scrollBy(0, delta);
809            }
810        }
811    }
812
813    /**
814     * Like {@link View#scrollBy}, but scroll smoothly instead of immediately.
815     *
816     * @param dx the number of pixels to scroll by on the X axis
817     * @param dy the number of pixels to scroll by on the Y axis
818     */
819    public final void smoothScrollBy(int dx, int dy) {
820        if (getChildCount() == 0) {
821            // Nothing to do.
822            return;
823        }
824        long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll;
825        if (duration > ANIMATED_SCROLL_GAP) {
826            final int height = getHeight() - mPaddingBottom - mPaddingTop;
827            final int bottom = getChildAt(0).getHeight();
828            final int maxY = Math.max(0, bottom - height);
829            final int scrollY = mScrollY;
830            dy = Math.max(0, Math.min(scrollY + dy, maxY)) - scrollY;
831
832            mScroller.startScroll(mScrollX, scrollY, 0, dy);
833            awakenScrollBars(mScroller.getDuration());
834            invalidate();
835        } else {
836            if (!mScroller.isFinished()) {
837                mScroller.abortAnimation();
838            }
839            scrollBy(dx, dy);
840        }
841        mLastScroll = AnimationUtils.currentAnimationTimeMillis();
842    }
843
844    /**
845     * Like {@link #scrollTo}, but scroll smoothly instead of immediately.
846     *
847     * @param x the position where to scroll on the X axis
848     * @param y the position where to scroll on the Y axis
849     */
850    public final void smoothScrollTo(int x, int y) {
851        smoothScrollBy(x - mScrollX, y - mScrollY);
852    }
853
854    /**
855     * <p>The scroll range of a scroll view is the overall height of all of its
856     * children.</p>
857     */
858    @Override
859    protected int computeVerticalScrollRange() {
860        int count = getChildCount();
861        return count == 0 ? getHeight() : (getChildAt(0)).getBottom();
862    }
863
864
865    @Override
866    protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) {
867        ViewGroup.LayoutParams lp = child.getLayoutParams();
868
869        int childWidthMeasureSpec;
870        int childHeightMeasureSpec;
871
872        childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, mPaddingLeft
873                + mPaddingRight, lp.width);
874
875        childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
876
877        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
878    }
879
880    @Override
881    protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed,
882            int parentHeightMeasureSpec, int heightUsed) {
883        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
884
885        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
886                mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
887                        + widthUsed, lp.width);
888        final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
889                lp.topMargin + lp.bottomMargin, MeasureSpec.UNSPECIFIED);
890
891        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
892    }
893
894    @Override
895    public void computeScroll() {
896        if (mScroller.computeScrollOffset()) {
897            // This is called at drawing time by ViewGroup.  We don't want to
898            // re-show the scrollbars at this point, which scrollTo will do,
899            // so we replicate most of scrollTo here.
900            //
901            //         It's a little odd to call onScrollChanged from inside the drawing.
902            //
903            //         It is, except when you remember that computeScroll() is used to
904            //         animate scrolling. So unless we want to defer the onScrollChanged()
905            //         until the end of the animated scrolling, we don't really have a
906            //         choice here.
907            //
908            //         I agree.  The alternative, which I think would be worse, is to post
909            //         something and tell the subclasses later.  This is bad because there
910            //         will be a window where mScrollX/Y is different from what the app
911            //         thinks it is.
912            //
913            int oldX = mScrollX;
914            int oldY = mScrollY;
915            int x = mScroller.getCurrX();
916            int y = mScroller.getCurrY();
917
918            mScrollX = x;
919            mScrollY = y;
920
921            if (oldX != mScrollX || oldY != mScrollY) {
922                onScrollChanged(mScrollX, mScrollY, oldX, oldY);
923            }
924
925            // Keep on drawing until the animation has finished.
926            postInvalidate();
927        }
928    }
929
930    /**
931     * Scrolls the view to the given child.
932     *
933     * @param child the View to scroll to
934     */
935    private void scrollToChild(View child) {
936        child.getDrawingRect(mTempRect);
937
938        /* Offset from child's local coordinates to ScrollView coordinates */
939        offsetDescendantRectToMyCoords(child, mTempRect);
940
941        int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
942
943        if (scrollDelta != 0) {
944            scrollBy(0, scrollDelta);
945        }
946    }
947
948    /**
949     * If rect is off screen, scroll just enough to get it (or at least the
950     * first screen size chunk of it) on screen.
951     *
952     * @param rect      The rectangle.
953     * @param immediate True to scroll immediately without animation
954     * @return true if scrolling was performed
955     */
956    private boolean scrollToChildRect(Rect rect, boolean immediate) {
957        final int delta = computeScrollDeltaToGetChildRectOnScreen(rect);
958        final boolean scroll = delta != 0;
959        if (scroll) {
960            if (immediate) {
961                scrollBy(0, delta);
962            } else {
963                smoothScrollBy(0, delta);
964            }
965        }
966        return scroll;
967    }
968
969    /**
970     * Compute the amount to scroll in the Y direction in order to get
971     * a rectangle completely on the screen (or, if taller than the screen,
972     * at least the first screen size chunk of it).
973     *
974     * @param rect The rect.
975     * @return The scroll delta.
976     */
977    protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) {
978        if (getChildCount() == 0) return 0;
979
980        int height = getHeight();
981        int screenTop = getScrollY();
982        int screenBottom = screenTop + height;
983
984        int fadingEdge = getVerticalFadingEdgeLength();
985
986        // leave room for top fading edge as long as rect isn't at very top
987        if (rect.top > 0) {
988            screenTop += fadingEdge;
989        }
990
991        // leave room for bottom fading edge as long as rect isn't at very bottom
992        if (rect.bottom < getChildAt(0).getHeight()) {
993            screenBottom -= fadingEdge;
994        }
995
996        int scrollYDelta = 0;
997
998        if (rect.bottom > screenBottom && rect.top > screenTop) {
999            // need to move down to get it in view: move down just enough so
1000            // that the entire rectangle is in view (or at least the first
1001            // screen size chunk).
1002
1003            if (rect.height() > height) {
1004                // just enough to get screen size chunk on
1005                scrollYDelta += (rect.top - screenTop);
1006            } else {
1007                // get entire rect at bottom of screen
1008                scrollYDelta += (rect.bottom - screenBottom);
1009            }
1010
1011            // make sure we aren't scrolling beyond the end of our content
1012            int bottom = getChildAt(0).getBottom();
1013            int distanceToBottom = bottom - screenBottom;
1014            scrollYDelta = Math.min(scrollYDelta, distanceToBottom);
1015
1016        } else if (rect.top < screenTop && rect.bottom < screenBottom) {
1017            // need to move up to get it in view: move up just enough so that
1018            // entire rectangle is in view (or at least the first screen
1019            // size chunk of it).
1020
1021            if (rect.height() > height) {
1022                // screen size chunk
1023                scrollYDelta -= (screenBottom - rect.bottom);
1024            } else {
1025                // entire rect at top
1026                scrollYDelta -= (screenTop - rect.top);
1027            }
1028
1029            // make sure we aren't scrolling any further than the top our content
1030            scrollYDelta = Math.max(scrollYDelta, -getScrollY());
1031        }
1032        return scrollYDelta;
1033    }
1034
1035    @Override
1036    public void requestChildFocus(View child, View focused) {
1037        if (!mScrollViewMovedFocus) {
1038            if (!mIsLayoutDirty) {
1039                scrollToChild(focused);
1040            } else {
1041                // The child may not be laid out yet, we can't compute the scroll yet
1042                mChildToScrollTo = focused;
1043            }
1044        }
1045        super.requestChildFocus(child, focused);
1046    }
1047
1048
1049    /**
1050     * When looking for focus in children of a scroll view, need to be a little
1051     * more careful not to give focus to something that is scrolled off screen.
1052     *
1053     * This is more expensive than the default {@link android.view.ViewGroup}
1054     * implementation, otherwise this behavior might have been made the default.
1055     */
1056    @Override
1057    protected boolean onRequestFocusInDescendants(int direction,
1058            Rect previouslyFocusedRect) {
1059
1060        // convert from forward / backward notation to up / down / left / right
1061        // (ugh).
1062        if (direction == View.FOCUS_FORWARD) {
1063            direction = View.FOCUS_DOWN;
1064        } else if (direction == View.FOCUS_BACKWARD) {
1065            direction = View.FOCUS_UP;
1066        }
1067
1068        final View nextFocus = previouslyFocusedRect == null ?
1069                FocusFinder.getInstance().findNextFocus(this, null, direction) :
1070                FocusFinder.getInstance().findNextFocusFromRect(this,
1071                        previouslyFocusedRect, direction);
1072
1073        if (nextFocus == null) {
1074            return false;
1075        }
1076
1077        if (isOffScreen(nextFocus)) {
1078            return false;
1079        }
1080
1081        return nextFocus.requestFocus(direction, previouslyFocusedRect);
1082    }
1083
1084    @Override
1085    public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
1086            boolean immediate) {
1087        // offset into coordinate space of this scroll view
1088        rectangle.offset(child.getLeft() - child.getScrollX(),
1089                child.getTop() - child.getScrollY());
1090
1091        return scrollToChildRect(rectangle, immediate);
1092    }
1093
1094    @Override
1095    public void requestLayout() {
1096        mIsLayoutDirty = true;
1097        super.requestLayout();
1098    }
1099
1100    @Override
1101    protected void onLayout(boolean changed, int l, int t, int r, int b) {
1102        super.onLayout(changed, l, t, r, b);
1103        mIsLayoutDirty = false;
1104        // Give a child focus if it needs it
1105        if (mChildToScrollTo != null && isViewDescendantOf(mChildToScrollTo, this)) {
1106                scrollToChild(mChildToScrollTo);
1107        }
1108        mChildToScrollTo = null;
1109
1110        // Calling this with the present values causes it to re-clam them
1111        scrollTo(mScrollX, mScrollY);
1112    }
1113
1114    @Override
1115    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
1116        super.onSizeChanged(w, h, oldw, oldh);
1117
1118        View currentFocused = findFocus();
1119        if (null == currentFocused || this == currentFocused)
1120            return;
1121
1122        // If the currently-focused view was visible on the screen when the
1123        // screen was at the old height, then scroll the screen to make that
1124        // view visible with the new screen height.
1125        if (isWithinDeltaOfScreen(currentFocused, 0, oldh)) {
1126            currentFocused.getDrawingRect(mTempRect);
1127            offsetDescendantRectToMyCoords(currentFocused, mTempRect);
1128            int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
1129            doScrollY(scrollDelta);
1130        }
1131    }
1132
1133    /**
1134     * Return true if child is an descendant of parent, (or equal to the parent).
1135     */
1136    private boolean isViewDescendantOf(View child, View parent) {
1137        if (child == parent) {
1138            return true;
1139        }
1140
1141        final ViewParent theParent = child.getParent();
1142        return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1143    }
1144
1145    /**
1146     * Fling the scroll view
1147     *
1148     * @param velocityY The initial velocity in the Y direction. Positive
1149     *                  numbers mean that the finger/curor is moving down the screen,
1150     *                  which means we want to scroll towards the top.
1151     */
1152    public void fling(int velocityY) {
1153        if (getChildCount() > 0) {
1154            int height = getHeight() - mPaddingBottom - mPaddingTop;
1155            int bottom = getChildAt(0).getHeight();
1156
1157            mScroller.fling(mScrollX, mScrollY, 0, velocityY, 0, 0, 0,
1158                    Math.max(0, bottom - height), 0, height/2);
1159
1160            final boolean movingDown = velocityY > 0;
1161
1162            View newFocused =
1163                    findFocusableViewInMyBounds(movingDown, mScroller.getFinalY(), findFocus());
1164            if (newFocused == null) {
1165                newFocused = this;
1166            }
1167
1168            if (newFocused != findFocus()
1169                    && newFocused.requestFocus(movingDown ? View.FOCUS_DOWN : View.FOCUS_UP)) {
1170                mScrollViewMovedFocus = true;
1171                mScrollViewMovedFocus = false;
1172            }
1173
1174            awakenScrollBars(mScroller.getDuration());
1175            invalidate();
1176        }
1177    }
1178
1179    /**
1180     * {@inheritDoc}
1181     *
1182     * <p>This version also clamps the scrolling to the bounds of our child.
1183     */
1184    public void scrollTo(int x, int y) {
1185        // we rely on the fact the View.scrollBy calls scrollTo.
1186        if (getChildCount() > 0) {
1187            View child = getChildAt(0);
1188            x = clamp(x, getWidth() - mPaddingRight - mPaddingLeft, child.getWidth());
1189            y = clamp(y, getHeight() - mPaddingBottom - mPaddingTop, child.getHeight());
1190            if (x != mScrollX || y != mScrollY) {
1191                super.scrollTo(x, y);
1192            }
1193        }
1194    }
1195
1196    private int clamp(int n, int my, int child) {
1197        if (my >= child || n < 0) {
1198            /* my >= child is this case:
1199             *                    |--------------- me ---------------|
1200             *     |------ child ------|
1201             * or
1202             *     |--------------- me ---------------|
1203             *            |------ child ------|
1204             * or
1205             *     |--------------- me ---------------|
1206             *                                  |------ child ------|
1207             *
1208             * n < 0 is this case:
1209             *     |------ me ------|
1210             *                    |-------- child --------|
1211             *     |-- mScrollX --|
1212             */
1213            return 0;
1214        }
1215        if ((my+n) > child) {
1216            /* this case:
1217             *                    |------ me ------|
1218             *     |------ child ------|
1219             *     |-- mScrollX --|
1220             */
1221            return child-my;
1222        }
1223        return n;
1224    }
1225}
1226