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