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