ScrollView.java revision 83d570cb3f1cc59d5a72e608b04d8f666db327a7
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 View child = getChildAt(0);
374            return !(y < child.getTop()
375                    || y >= child.getBottom()
376                    || x < child.getLeft()
377                    || x >= child.getRight());
378        }
379        return false;
380    }
381
382    @Override
383    public boolean onInterceptTouchEvent(MotionEvent ev) {
384        /*
385         * This method JUST determines whether we want to intercept the motion.
386         * If we return true, onMotionEvent will be called and we do the actual
387         * scrolling there.
388         */
389
390        /*
391        * Shortcut the most recurring case: the user is in the dragging
392        * state and he is moving his finger.  We want to intercept this
393        * motion.
394        */
395        final int action = ev.getAction();
396        if ((action == MotionEvent.ACTION_MOVE) && (mIsBeingDragged)) {
397            return true;
398        }
399
400        switch (action & MotionEvent.ACTION_MASK) {
401            case MotionEvent.ACTION_MOVE: {
402                /*
403                 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
404                 * whether the user has moved far enough from his original down touch.
405                 */
406
407                /*
408                * Locally do absolute value. mLastMotionY is set to the y value
409                * of the down event.
410                */
411                final int pointerIndex = ev.findPointerIndex(mActivePointerId);
412                final float y = ev.getY(pointerIndex);
413                final int yDiff = (int) Math.abs(y - mLastMotionY);
414                if (yDiff > mTouchSlop) {
415                    mIsBeingDragged = true;
416                    mLastMotionY = y;
417                }
418                break;
419            }
420
421            case MotionEvent.ACTION_DOWN: {
422                final float y = ev.getY();
423                if (!inChild((int) ev.getX(), (int) y)) {
424                    mIsBeingDragged = false;
425                    break;
426                }
427
428                /*
429                 * Remember location of down touch.
430                 * ACTION_DOWN always refers to pointer index 0.
431                 */
432                mLastMotionY = y;
433                mActivePointerId = ev.getPointerId(0);
434
435                /*
436                * If being flinged and user touches the screen, initiate drag;
437                * otherwise don't.  mScroller.isFinished should be false when
438                * being flinged.
439                */
440                mIsBeingDragged = !mScroller.isFinished();
441                break;
442            }
443
444            case MotionEvent.ACTION_CANCEL:
445            case MotionEvent.ACTION_UP:
446                /* Release the drag */
447                mIsBeingDragged = false;
448                mActivePointerId = INVALID_POINTER;
449                break;
450            case MotionEvent.ACTION_POINTER_UP:
451                onSecondaryPointerUp(ev);
452                break;
453        }
454
455        /*
456        * The only time we want to intercept motion events is if we are in the
457        * drag mode.
458        */
459        return mIsBeingDragged;
460    }
461
462    @Override
463    public boolean onTouchEvent(MotionEvent ev) {
464
465        if (ev.getAction() == MotionEvent.ACTION_DOWN && ev.getEdgeFlags() != 0) {
466            // Don't handle edge touches immediately -- they may actually belong to one of our
467            // descendants.
468            return false;
469        }
470
471        if (mVelocityTracker == null) {
472            mVelocityTracker = VelocityTracker.obtain();
473        }
474        mVelocityTracker.addMovement(ev);
475
476        final int action = ev.getAction();
477
478        switch (action & MotionEvent.ACTION_MASK) {
479            case MotionEvent.ACTION_DOWN: {
480                /*
481                * If being flinged and user touches, stop the fling. isFinished
482                * will be false if being flinged.
483                */
484                if (!mScroller.isFinished()) {
485                    mScroller.abortAnimation();
486                }
487
488                final float y = ev.getY();
489                if (!(mIsBeingDragged = inChild((int) ev.getX(), (int) y))) {
490                    return false;
491                }
492
493                // Remember where the motion event started
494                mLastMotionY = y;
495                mActivePointerId = ev.getPointerId(0);
496                break;
497            }
498            case MotionEvent.ACTION_MOVE:
499                if (mIsBeingDragged) {
500                    // Scroll to follow the motion event
501                    final int activePointerIndex = ev.findPointerIndex(mActivePointerId);
502                    final float y = ev.getY(activePointerIndex);
503                    final int deltaY = (int) (mLastMotionY - y);
504                    mLastMotionY = y;
505
506                    final int oldX = mScrollX;
507                    final int oldY = mScrollY;
508                    overscrollBy(0, deltaY, 0, mScrollY, 0, getScrollRange(),
509                            0, getOverscrollMax(), true);
510                    onScrollChanged(mScrollX, mScrollY, oldX, oldY);
511                }
512                break;
513            case MotionEvent.ACTION_UP:
514                if (mIsBeingDragged) {
515                    final VelocityTracker velocityTracker = mVelocityTracker;
516                    velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
517                    int initialVelocity = (int) velocityTracker.getYVelocity(mActivePointerId);
518
519                    if (getChildCount() > 0) {
520                        if ((Math.abs(initialVelocity) > mMinimumVelocity)) {
521                            fling(-initialVelocity);
522                        } else {
523                            final int bottom = getScrollRange();
524                            if (mScroller.springback(mScrollX, mScrollY, 0, 0, 0, bottom)) {
525                                invalidate();
526                            }
527                        }
528                    }
529
530                    mActivePointerId = INVALID_POINTER;
531                    mIsBeingDragged = false;
532
533                    if (mVelocityTracker != null) {
534                        mVelocityTracker.recycle();
535                        mVelocityTracker = null;
536                    }
537                }
538                break;
539            case MotionEvent.ACTION_POINTER_UP:
540                onSecondaryPointerUp(ev);
541                break;
542        }
543        return true;
544    }
545
546    private void onSecondaryPointerUp(MotionEvent ev) {
547        final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
548                MotionEvent.ACTION_POINTER_INDEX_SHIFT;
549        final int pointerId = ev.getPointerId(pointerIndex);
550        if (pointerId == mActivePointerId) {
551            // This was our active pointer going up. Choose a new
552            // active pointer and adjust accordingly.
553            // TODO: Make this decision more intelligent.
554            final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
555            mLastMotionY = ev.getY(newPointerIndex);
556            mActivePointerId = ev.getPointerId(newPointerIndex);
557            if (mVelocityTracker != null) {
558                mVelocityTracker.clear();
559            }
560        }
561    }
562
563    @Override
564    protected void onOverscrolled(int scrollX, int scrollY,
565            boolean clampedX, boolean clampedY) {
566        // Treat animating scrolls differently; see #computeScroll() for why.
567        if (!mScroller.isFinished()) {
568            mScrollX = scrollX;
569            mScrollY = scrollY;
570            if (clampedY) {
571                mScroller.springback(mScrollX, mScrollY, 0, 0, 0, getScrollRange());
572            }
573        } else {
574            super.scrollTo(scrollX, scrollY);
575        }
576        awakenScrollBars();
577    }
578
579    private int getOverscrollMax() {
580        int childCount = getChildCount();
581        int containerOverscroll = (getHeight() - mPaddingBottom - mPaddingTop) / 3;
582        if (childCount > 0) {
583            return Math.min(containerOverscroll, getChildAt(0).getHeight() / 3);
584        } else {
585            return containerOverscroll;
586        }
587    }
588
589    private int getScrollRange() {
590        int scrollRange = 0;
591        if (getChildCount() > 0) {
592            View child = getChildAt(0);
593            scrollRange = Math.max(0,
594                    child.getHeight() - getHeight() - mPaddingBottom - mPaddingTop);
595        }
596        return scrollRange;
597    }
598
599    /**
600     * <p>
601     * Finds the next focusable component that fits in this View's bounds
602     * (excluding fading edges) pretending that this View's top is located at
603     * the parameter top.
604     * </p>
605     *
606     * @param topFocus           look for a candidate is the one at the top of the bounds
607     *                           if topFocus is true, or at the bottom of the bounds if topFocus is
608     *                           false
609     * @param top                the top offset of the bounds in which a focusable must be
610     *                           found (the fading edge is assumed to start at this position)
611     * @param preferredFocusable the View that has highest priority and will be
612     *                           returned if it is within my bounds (null is valid)
613     * @return the next focusable component in the bounds or null if none can be
614     *         found
615     */
616    private View findFocusableViewInMyBounds(final boolean topFocus,
617            final int top, View preferredFocusable) {
618        /*
619         * The fading edge's transparent side should be considered for focus
620         * since it's mostly visible, so we divide the actual fading edge length
621         * by 2.
622         */
623        final int fadingEdgeLength = getVerticalFadingEdgeLength() / 2;
624        final int topWithoutFadingEdge = top + fadingEdgeLength;
625        final int bottomWithoutFadingEdge = top + getHeight() - fadingEdgeLength;
626
627        if ((preferredFocusable != null)
628                && (preferredFocusable.getTop() < bottomWithoutFadingEdge)
629                && (preferredFocusable.getBottom() > topWithoutFadingEdge)) {
630            return preferredFocusable;
631        }
632
633        return findFocusableViewInBounds(topFocus, topWithoutFadingEdge,
634                bottomWithoutFadingEdge);
635    }
636
637    /**
638     * <p>
639     * Finds the next focusable component that fits in the specified bounds.
640     * </p>
641     *
642     * @param topFocus look for a candidate is the one at the top of the bounds
643     *                 if topFocus is true, or at the bottom of the bounds if topFocus is
644     *                 false
645     * @param top      the top offset of the bounds in which a focusable must be
646     *                 found
647     * @param bottom   the bottom offset of the bounds in which a focusable must
648     *                 be found
649     * @return the next focusable component in the bounds or null if none can
650     *         be found
651     */
652    private View findFocusableViewInBounds(boolean topFocus, int top, int bottom) {
653
654        List<View> focusables = getFocusables(View.FOCUS_FORWARD);
655        View focusCandidate = null;
656
657        /*
658         * A fully contained focusable is one where its top is below the bound's
659         * top, and its bottom is above the bound's bottom. A partially
660         * contained focusable is one where some part of it is within the
661         * bounds, but it also has some part that is not within bounds.  A fully contained
662         * focusable is preferred to a partially contained focusable.
663         */
664        boolean foundFullyContainedFocusable = false;
665
666        int count = focusables.size();
667        for (int i = 0; i < count; i++) {
668            View view = focusables.get(i);
669            int viewTop = view.getTop();
670            int viewBottom = view.getBottom();
671
672            if (top < viewBottom && viewTop < bottom) {
673                /*
674                 * the focusable is in the target area, it is a candidate for
675                 * focusing
676                 */
677
678                final boolean viewIsFullyContained = (top < viewTop) &&
679                        (viewBottom < bottom);
680
681                if (focusCandidate == null) {
682                    /* No candidate, take this one */
683                    focusCandidate = view;
684                    foundFullyContainedFocusable = viewIsFullyContained;
685                } else {
686                    final boolean viewIsCloserToBoundary =
687                            (topFocus && viewTop < focusCandidate.getTop()) ||
688                                    (!topFocus && viewBottom > focusCandidate
689                                            .getBottom());
690
691                    if (foundFullyContainedFocusable) {
692                        if (viewIsFullyContained && viewIsCloserToBoundary) {
693                            /*
694                             * We're dealing with only fully contained views, so
695                             * it has to be closer to the boundary to beat our
696                             * candidate
697                             */
698                            focusCandidate = view;
699                        }
700                    } else {
701                        if (viewIsFullyContained) {
702                            /* Any fully contained view beats a partially contained view */
703                            focusCandidate = view;
704                            foundFullyContainedFocusable = true;
705                        } else if (viewIsCloserToBoundary) {
706                            /*
707                             * Partially contained view beats another partially
708                             * contained view if it's closer
709                             */
710                            focusCandidate = view;
711                        }
712                    }
713                }
714            }
715        }
716
717        return focusCandidate;
718    }
719
720    /**
721     * <p>Handles scrolling in response to a "page up/down" shortcut press. This
722     * method will scroll the view by one page up or down and give the focus
723     * to the topmost/bottommost component in the new visible area. If no
724     * component is a good candidate for focus, this scrollview reclaims the
725     * focus.</p>
726     *
727     * @param direction the scroll direction: {@link android.view.View#FOCUS_UP}
728     *                  to go one page up or
729     *                  {@link android.view.View#FOCUS_DOWN} to go one page down
730     * @return true if the key event is consumed by this method, false otherwise
731     */
732    public boolean pageScroll(int direction) {
733        boolean down = direction == View.FOCUS_DOWN;
734        int height = getHeight();
735
736        if (down) {
737            mTempRect.top = getScrollY() + height;
738            int count = getChildCount();
739            if (count > 0) {
740                View view = getChildAt(count - 1);
741                if (mTempRect.top + height > view.getBottom()) {
742                    mTempRect.top = view.getBottom() - height;
743                }
744            }
745        } else {
746            mTempRect.top = getScrollY() - height;
747            if (mTempRect.top < 0) {
748                mTempRect.top = 0;
749            }
750        }
751        mTempRect.bottom = mTempRect.top + height;
752
753        return scrollAndFocus(direction, mTempRect.top, mTempRect.bottom);
754    }
755
756    /**
757     * <p>Handles scrolling in response to a "home/end" shortcut press. This
758     * method will scroll the view to the top or bottom and give the focus
759     * to the topmost/bottommost component in the new visible area. If no
760     * component is a good candidate for focus, this scrollview reclaims the
761     * focus.</p>
762     *
763     * @param direction the scroll direction: {@link android.view.View#FOCUS_UP}
764     *                  to go the top of the view or
765     *                  {@link android.view.View#FOCUS_DOWN} to go the bottom
766     * @return true if the key event is consumed by this method, false otherwise
767     */
768    public boolean fullScroll(int direction) {
769        boolean down = direction == View.FOCUS_DOWN;
770        int height = getHeight();
771
772        mTempRect.top = 0;
773        mTempRect.bottom = height;
774
775        if (down) {
776            int count = getChildCount();
777            if (count > 0) {
778                View view = getChildAt(count - 1);
779                mTempRect.bottom = view.getBottom();
780                mTempRect.top = mTempRect.bottom - height;
781            }
782        }
783
784        return scrollAndFocus(direction, mTempRect.top, mTempRect.bottom);
785    }
786
787    /**
788     * <p>Scrolls the view to make the area defined by <code>top</code> and
789     * <code>bottom</code> visible. This method attempts to give the focus
790     * to a component visible in this area. If no component can be focused in
791     * the new visible area, the focus is reclaimed by this scrollview.</p>
792     *
793     * @param direction the scroll direction: {@link android.view.View#FOCUS_UP}
794     *                  to go upward
795     *                  {@link android.view.View#FOCUS_DOWN} to downward
796     * @param top       the top offset of the new area to be made visible
797     * @param bottom    the bottom offset of the new area to be made visible
798     * @return true if the key event is consumed by this method, false otherwise
799     */
800    private boolean scrollAndFocus(int direction, int top, int bottom) {
801        boolean handled = true;
802
803        int height = getHeight();
804        int containerTop = getScrollY();
805        int containerBottom = containerTop + height;
806        boolean up = direction == View.FOCUS_UP;
807
808        View newFocused = findFocusableViewInBounds(up, top, bottom);
809        if (newFocused == null) {
810            newFocused = this;
811        }
812
813        if (top >= containerTop && bottom <= containerBottom) {
814            handled = false;
815        } else {
816            int delta = up ? (top - containerTop) : (bottom - containerBottom);
817            doScrollY(delta);
818        }
819
820        if (newFocused != findFocus() && newFocused.requestFocus(direction)) {
821            mScrollViewMovedFocus = true;
822            mScrollViewMovedFocus = false;
823        }
824
825        return handled;
826    }
827
828    /**
829     * Handle scrolling in response to an up or down arrow click.
830     *
831     * @param direction The direction corresponding to the arrow key that was
832     *                  pressed
833     * @return True if we consumed the event, false otherwise
834     */
835    public boolean arrowScroll(int direction) {
836
837        View currentFocused = findFocus();
838        if (currentFocused == this) currentFocused = null;
839
840        View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, direction);
841
842        final int maxJump = getMaxScrollAmount();
843
844        if (nextFocused != null && isWithinDeltaOfScreen(nextFocused, maxJump, getHeight())) {
845            nextFocused.getDrawingRect(mTempRect);
846            offsetDescendantRectToMyCoords(nextFocused, mTempRect);
847            int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
848            doScrollY(scrollDelta);
849            nextFocused.requestFocus(direction);
850        } else {
851            // no new focus
852            int scrollDelta = maxJump;
853
854            if (direction == View.FOCUS_UP && getScrollY() < scrollDelta) {
855                scrollDelta = getScrollY();
856            } else if (direction == View.FOCUS_DOWN) {
857                if (getChildCount() > 0) {
858                    int daBottom = getChildAt(0).getBottom();
859
860                    int screenBottom = getScrollY() + getHeight();
861
862                    if (daBottom - screenBottom < maxJump) {
863                        scrollDelta = daBottom - screenBottom;
864                    }
865                }
866            }
867            if (scrollDelta == 0) {
868                return false;
869            }
870            doScrollY(direction == View.FOCUS_DOWN ? scrollDelta : -scrollDelta);
871        }
872
873        if (currentFocused != null && currentFocused.isFocused()
874                && isOffScreen(currentFocused)) {
875            // previously focused item still has focus and is off screen, give
876            // it up (take it back to ourselves)
877            // (also, need to temporarily force FOCUS_BEFORE_DESCENDANTS so we are
878            // sure to
879            // get it)
880            final int descendantFocusability = getDescendantFocusability();  // save
881            setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
882            requestFocus();
883            setDescendantFocusability(descendantFocusability);  // restore
884        }
885        return true;
886    }
887
888    /**
889     * @return whether the descendant of this scroll view is scrolled off
890     *  screen.
891     */
892    private boolean isOffScreen(View descendant) {
893        return !isWithinDeltaOfScreen(descendant, 0, getHeight());
894    }
895
896    /**
897     * @return whether the descendant of this scroll view is within delta
898     *  pixels of being on the screen.
899     */
900    private boolean isWithinDeltaOfScreen(View descendant, int delta, int height) {
901        descendant.getDrawingRect(mTempRect);
902        offsetDescendantRectToMyCoords(descendant, mTempRect);
903
904        return (mTempRect.bottom + delta) >= getScrollY()
905                && (mTempRect.top - delta) <= (getScrollY() + height);
906    }
907
908    /**
909     * Smooth scroll by a Y delta
910     *
911     * @param delta the number of pixels to scroll by on the Y axis
912     */
913    private void doScrollY(int delta) {
914        if (delta != 0) {
915            if (mSmoothScrollingEnabled) {
916                smoothScrollBy(0, delta);
917            } else {
918                scrollBy(0, delta);
919            }
920        }
921    }
922
923    /**
924     * Like {@link View#scrollBy}, but scroll smoothly instead of immediately.
925     *
926     * @param dx the number of pixels to scroll by on the X axis
927     * @param dy the number of pixels to scroll by on the Y axis
928     */
929    public final void smoothScrollBy(int dx, int dy) {
930        if (getChildCount() == 0) {
931            // Nothing to do.
932            return;
933        }
934        long duration = AnimationUtils.currentAnimationTimeMillis() - mLastScroll;
935        if (duration > ANIMATED_SCROLL_GAP) {
936            final int height = getHeight() - mPaddingBottom - mPaddingTop;
937            final int bottom = getChildAt(0).getHeight();
938            final int maxY = Math.max(0, bottom - height);
939            final int scrollY = mScrollY;
940            dy = Math.max(0, Math.min(scrollY + dy, maxY)) - scrollY;
941
942            mScroller.startScroll(mScrollX, scrollY, 0, dy);
943            awakenScrollBars(mScroller.getDuration());
944            invalidate();
945        } else {
946            if (!mScroller.isFinished()) {
947                mScroller.abortAnimation();
948            }
949            scrollBy(dx, dy);
950        }
951        mLastScroll = AnimationUtils.currentAnimationTimeMillis();
952    }
953
954    /**
955     * Like {@link #scrollTo}, but scroll smoothly instead of immediately.
956     *
957     * @param x the position where to scroll on the X axis
958     * @param y the position where to scroll on the Y axis
959     */
960    public final void smoothScrollTo(int x, int y) {
961        smoothScrollBy(x - mScrollX, y - mScrollY);
962    }
963
964    /**
965     * <p>The scroll range of a scroll view is the overall height of all of its
966     * children.</p>
967     */
968    @Override
969    protected int computeVerticalScrollRange() {
970        final int count = getChildCount();
971        final int contentHeight = getHeight() - mPaddingBottom - mPaddingTop;
972        if (count == 0) {
973            return contentHeight;
974        }
975
976        int scrollRange = getChildAt(0).getBottom();
977        final int scrollY = mScrollY;
978        final int overscrollBottom = Math.max(0, scrollRange - contentHeight);
979        if (scrollY < 0) {
980            scrollRange -= scrollY;
981        } else if (scrollY > overscrollBottom) {
982            scrollRange += scrollY - overscrollBottom;
983        }
984
985        return scrollRange;
986    }
987
988    @Override
989    protected int computeVerticalScrollOffset() {
990        return Math.max(0, super.computeVerticalScrollOffset());
991    }
992
993    @Override
994    protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) {
995        ViewGroup.LayoutParams lp = child.getLayoutParams();
996
997        int childWidthMeasureSpec;
998        int childHeightMeasureSpec;
999
1000        childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, mPaddingLeft
1001                + mPaddingRight, lp.width);
1002
1003        childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
1004
1005        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1006    }
1007
1008    @Override
1009    protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed,
1010            int parentHeightMeasureSpec, int heightUsed) {
1011        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
1012
1013        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
1014                mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
1015                        + widthUsed, lp.width);
1016        final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
1017                lp.topMargin + lp.bottomMargin, MeasureSpec.UNSPECIFIED);
1018
1019        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
1020    }
1021
1022    @Override
1023    public void computeScroll() {
1024        if (mScroller.computeScrollOffset()) {
1025            // This is called at drawing time by ViewGroup.  We don't want to
1026            // re-show the scrollbars at this point, which scrollTo will do,
1027            // so we replicate most of scrollTo here.
1028            //
1029            //         It's a little odd to call onScrollChanged from inside the drawing.
1030            //
1031            //         It is, except when you remember that computeScroll() is used to
1032            //         animate scrolling. So unless we want to defer the onScrollChanged()
1033            //         until the end of the animated scrolling, we don't really have a
1034            //         choice here.
1035            //
1036            //         I agree.  The alternative, which I think would be worse, is to post
1037            //         something and tell the subclasses later.  This is bad because there
1038            //         will be a window where mScrollX/Y is different from what the app
1039            //         thinks it is.
1040            //
1041            int oldX = mScrollX;
1042            int oldY = mScrollY;
1043            int x = mScroller.getCurrX();
1044            int y = mScroller.getCurrY();
1045
1046            if (oldX != x || oldY != y) {
1047                overscrollBy(x - oldX, y - oldY, oldX, oldY, 0, getScrollRange(),
1048                        0, getOverscrollMax(), false);
1049                onScrollChanged(mScrollX, mScrollY, oldX, oldY);
1050            }
1051
1052            // Keep on drawing until the animation has finished.
1053            postInvalidate();
1054        }
1055    }
1056
1057    /**
1058     * Scrolls the view to the given child.
1059     *
1060     * @param child the View to scroll to
1061     */
1062    private void scrollToChild(View child) {
1063        child.getDrawingRect(mTempRect);
1064
1065        /* Offset from child's local coordinates to ScrollView coordinates */
1066        offsetDescendantRectToMyCoords(child, mTempRect);
1067
1068        int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
1069
1070        if (scrollDelta != 0) {
1071            scrollBy(0, scrollDelta);
1072        }
1073    }
1074
1075    /**
1076     * If rect is off screen, scroll just enough to get it (or at least the
1077     * first screen size chunk of it) on screen.
1078     *
1079     * @param rect      The rectangle.
1080     * @param immediate True to scroll immediately without animation
1081     * @return true if scrolling was performed
1082     */
1083    private boolean scrollToChildRect(Rect rect, boolean immediate) {
1084        final int delta = computeScrollDeltaToGetChildRectOnScreen(rect);
1085        final boolean scroll = delta != 0;
1086        if (scroll) {
1087            if (immediate) {
1088                scrollBy(0, delta);
1089            } else {
1090                smoothScrollBy(0, delta);
1091            }
1092        }
1093        return scroll;
1094    }
1095
1096    /**
1097     * Compute the amount to scroll in the Y direction in order to get
1098     * a rectangle completely on the screen (or, if taller than the screen,
1099     * at least the first screen size chunk of it).
1100     *
1101     * @param rect The rect.
1102     * @return The scroll delta.
1103     */
1104    protected int computeScrollDeltaToGetChildRectOnScreen(Rect rect) {
1105        if (getChildCount() == 0) return 0;
1106
1107        int height = getHeight();
1108        int screenTop = getScrollY();
1109        int screenBottom = screenTop + height;
1110
1111        int fadingEdge = getVerticalFadingEdgeLength();
1112
1113        // leave room for top fading edge as long as rect isn't at very top
1114        if (rect.top > 0) {
1115            screenTop += fadingEdge;
1116        }
1117
1118        // leave room for bottom fading edge as long as rect isn't at very bottom
1119        if (rect.bottom < getChildAt(0).getHeight()) {
1120            screenBottom -= fadingEdge;
1121        }
1122
1123        int scrollYDelta = 0;
1124
1125        if (rect.bottom > screenBottom && rect.top > screenTop) {
1126            // need to move down to get it in view: move down just enough so
1127            // that the entire rectangle is in view (or at least the first
1128            // screen size chunk).
1129
1130            if (rect.height() > height) {
1131                // just enough to get screen size chunk on
1132                scrollYDelta += (rect.top - screenTop);
1133            } else {
1134                // get entire rect at bottom of screen
1135                scrollYDelta += (rect.bottom - screenBottom);
1136            }
1137
1138            // make sure we aren't scrolling beyond the end of our content
1139            int bottom = getChildAt(0).getBottom();
1140            int distanceToBottom = bottom - screenBottom;
1141            scrollYDelta = Math.min(scrollYDelta, distanceToBottom);
1142
1143        } else if (rect.top < screenTop && rect.bottom < screenBottom) {
1144            // need to move up to get it in view: move up just enough so that
1145            // entire rectangle is in view (or at least the first screen
1146            // size chunk of it).
1147
1148            if (rect.height() > height) {
1149                // screen size chunk
1150                scrollYDelta -= (screenBottom - rect.bottom);
1151            } else {
1152                // entire rect at top
1153                scrollYDelta -= (screenTop - rect.top);
1154            }
1155
1156            // make sure we aren't scrolling any further than the top our content
1157            scrollYDelta = Math.max(scrollYDelta, -getScrollY());
1158        }
1159        return scrollYDelta;
1160    }
1161
1162    @Override
1163    public void requestChildFocus(View child, View focused) {
1164        if (!mScrollViewMovedFocus) {
1165            if (!mIsLayoutDirty) {
1166                scrollToChild(focused);
1167            } else {
1168                // The child may not be laid out yet, we can't compute the scroll yet
1169                mChildToScrollTo = focused;
1170            }
1171        }
1172        super.requestChildFocus(child, focused);
1173    }
1174
1175
1176    /**
1177     * When looking for focus in children of a scroll view, need to be a little
1178     * more careful not to give focus to something that is scrolled off screen.
1179     *
1180     * This is more expensive than the default {@link android.view.ViewGroup}
1181     * implementation, otherwise this behavior might have been made the default.
1182     */
1183    @Override
1184    protected boolean onRequestFocusInDescendants(int direction,
1185            Rect previouslyFocusedRect) {
1186
1187        // convert from forward / backward notation to up / down / left / right
1188        // (ugh).
1189        if (direction == View.FOCUS_FORWARD) {
1190            direction = View.FOCUS_DOWN;
1191        } else if (direction == View.FOCUS_BACKWARD) {
1192            direction = View.FOCUS_UP;
1193        }
1194
1195        final View nextFocus = previouslyFocusedRect == null ?
1196                FocusFinder.getInstance().findNextFocus(this, null, direction) :
1197                FocusFinder.getInstance().findNextFocusFromRect(this,
1198                        previouslyFocusedRect, direction);
1199
1200        if (nextFocus == null) {
1201            return false;
1202        }
1203
1204        if (isOffScreen(nextFocus)) {
1205            return false;
1206        }
1207
1208        return nextFocus.requestFocus(direction, previouslyFocusedRect);
1209    }
1210
1211    @Override
1212    public boolean requestChildRectangleOnScreen(View child, Rect rectangle,
1213            boolean immediate) {
1214        // offset into coordinate space of this scroll view
1215        rectangle.offset(child.getLeft() - child.getScrollX(),
1216                child.getTop() - child.getScrollY());
1217
1218        return scrollToChildRect(rectangle, immediate);
1219    }
1220
1221    @Override
1222    public void requestLayout() {
1223        mIsLayoutDirty = true;
1224        super.requestLayout();
1225    }
1226
1227    @Override
1228    protected void onLayout(boolean changed, int l, int t, int r, int b) {
1229        super.onLayout(changed, l, t, r, b);
1230        mIsLayoutDirty = false;
1231        // Give a child focus if it needs it
1232        if (mChildToScrollTo != null && isViewDescendantOf(mChildToScrollTo, this)) {
1233                scrollToChild(mChildToScrollTo);
1234        }
1235        mChildToScrollTo = null;
1236
1237        // Calling this with the present values causes it to re-clam them
1238        scrollTo(mScrollX, mScrollY);
1239    }
1240
1241    @Override
1242    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
1243        super.onSizeChanged(w, h, oldw, oldh);
1244
1245        View currentFocused = findFocus();
1246        if (null == currentFocused || this == currentFocused)
1247            return;
1248
1249        // If the currently-focused view was visible on the screen when the
1250        // screen was at the old height, then scroll the screen to make that
1251        // view visible with the new screen height.
1252        if (isWithinDeltaOfScreen(currentFocused, 0, oldh)) {
1253            currentFocused.getDrawingRect(mTempRect);
1254            offsetDescendantRectToMyCoords(currentFocused, mTempRect);
1255            int scrollDelta = computeScrollDeltaToGetChildRectOnScreen(mTempRect);
1256            doScrollY(scrollDelta);
1257        }
1258    }
1259
1260    /**
1261     * Return true if child is an descendant of parent, (or equal to the parent).
1262     */
1263    private boolean isViewDescendantOf(View child, View parent) {
1264        if (child == parent) {
1265            return true;
1266        }
1267
1268        final ViewParent theParent = child.getParent();
1269        return (theParent instanceof ViewGroup) && isViewDescendantOf((View) theParent, parent);
1270    }
1271
1272    /**
1273     * Fling the scroll view
1274     *
1275     * @param velocityY The initial velocity in the Y direction. Positive
1276     *                  numbers mean that the finger/cursor is moving down the screen,
1277     *                  which means we want to scroll towards the top.
1278     */
1279    public void fling(int velocityY) {
1280        if (getChildCount() > 0) {
1281            int height = getHeight() - mPaddingBottom - mPaddingTop;
1282            int bottom = getChildAt(0).getHeight();
1283
1284            mScroller.fling(mScrollX, mScrollY, 0, velocityY, 0, 0, 0,
1285                    Math.max(0, bottom - height), 0, height/2);
1286
1287            final boolean movingDown = velocityY > 0;
1288
1289            View newFocused =
1290                    findFocusableViewInMyBounds(movingDown, mScroller.getFinalY(), findFocus());
1291            if (newFocused == null) {
1292                newFocused = this;
1293            }
1294
1295            if (newFocused != findFocus()
1296                    && newFocused.requestFocus(movingDown ? View.FOCUS_DOWN : View.FOCUS_UP)) {
1297                mScrollViewMovedFocus = true;
1298                mScrollViewMovedFocus = false;
1299            }
1300
1301            invalidate();
1302        }
1303    }
1304
1305    /**
1306     * {@inheritDoc}
1307     *
1308     * <p>This version also clamps the scrolling to the bounds of our child.
1309     */
1310    @Override
1311    public void scrollTo(int x, int y) {
1312        // we rely on the fact the View.scrollBy calls scrollTo.
1313        if (getChildCount() > 0) {
1314            View child = getChildAt(0);
1315            x = clamp(x, getWidth() - mPaddingRight - mPaddingLeft, child.getWidth());
1316            y = clamp(y, getHeight() - mPaddingBottom - mPaddingTop, child.getHeight());
1317            if (x != mScrollX || y != mScrollY) {
1318                super.scrollTo(x, y);
1319            }
1320        }
1321    }
1322
1323    private int clamp(int n, int my, int child) {
1324        if (my >= child || n < 0) {
1325            /* my >= child is this case:
1326             *                    |--------------- me ---------------|
1327             *     |------ child ------|
1328             * or
1329             *     |--------------- me ---------------|
1330             *            |------ child ------|
1331             * or
1332             *     |--------------- me ---------------|
1333             *                                  |------ child ------|
1334             *
1335             * n < 0 is this case:
1336             *     |------ me ------|
1337             *                    |-------- child --------|
1338             *     |-- mScrollX --|
1339             */
1340            return 0;
1341        }
1342        if ((my+n) > child) {
1343            /* this case:
1344             *                    |------ me ------|
1345             *     |------ child ------|
1346             *     |-- mScrollX --|
1347             */
1348            return child-my;
1349        }
1350        return n;
1351    }
1352}
1353