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